net/http
Golang 标准库 - net/http
net/http 包提供了 HTTP 客户端和服务端的实现。支持 HTTP/1.1 和 HTTP/2。
主要功能说明:
-
HTTP 客户端:
Get()/Post()简单请求NewRequest()创建自定义请求Client自定义客户端配置Do()执行请求
-
HTTP 服务端:
HandleFunc()注册处理函数Handle()注册处理程序ListenAndServe()启动服务Server自定义服务器配置
-
请求与响应:
RequestHTTP 请求ResponseHTTP 响应Header请求/响应头
-
中间件与路由:
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()
}