wx

关注公众号

net/http


Golang 标准库 - net/http

net/http 包提供了 HTTP 客户端和服务端的实现。支持 HTTP/1.1 和 HTTP/2。

主要功能说明:

  1. HTTP 客户端

    • Get()/Post() 简单请求
    • NewRequest() 创建自定义请求
    • Client 自定义客户端配置
    • Do() 执行请求
  2. HTTP 服务端

    • HandleFunc() 注册处理函数
    • Handle() 注册处理程序
    • ListenAndServe() 启动服务
    • Server 自定义服务器配置
  3. 请求与响应

    • Request HTTP 请求
    • Response HTTP 响应
    • Header 请求/响应头
  4. 中间件与路由

    • ServeMux 多路复用器
    • Handler 接口

// HTTP 客户端示例
func HttpClientDemo() {
	// 简单 GET 请求
	resp, err := http.Get("https://api.github.com/users/github")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("Status: %s, Length: %d\n", resp.Status, len(body))

	// 带超时和 Header 的请求
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	req, _ := http.NewRequest("GET", "https://api.github.com", nil)
	req.Header.Set("Accept", "application/json")
	req.Header.Set("User-Agent", "Go-http-client")

	resp, err = client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	fmt.Println("自定义请求状态:", resp.Status)
}

// HTTP 服务端示例
func HttpServerDemo() {
	// 注册处理函数
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, World! Method: %s\n", r.Method)
	})

	http.HandleFunc("/user/", func(w http.ResponseWriter, r *http.Request) {
		name := r.URL.Path[len("/user/"):]
		fmt.Fprintf(w, "Hello, %s!\n", name)
	})

	http.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		data := map[string]string{"message": "success", "status": "ok"}
		json.NewEncoder(w).Encode(data)
	})

	// POST 处理器
	http.HandleFunc("/submit", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		
		body, _ := io.ReadAll(r.Body)
		fmt.Fprintf(w, "Received: %s\n", string(body))
	})

	fmt.Println("Server starting on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 中间件示例
type Middleware func(http.Handler) http.Handler

func LoggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
	})
}

func main() {
	// 客户端演示
	HttpClientDemo()

	// 服务端演示(取消注释运行)
	// HttpServerDemo()
}
如有疑问关注公众号给我留言
wx

关注公众号

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo