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()
}
🛒 站长推荐(京东联盟)
- 《Go 程序设计语言》(Go 语言圣经,机械工业出版社) —— Go 官方团队出品,公认入门第一书
- 《Go 语言实战》(异步图书,人民邮电出版社) —— 实战导向,面试前巩固工程手感
- 《Go 语言编程之旅:一起用 Go 做项目》(博文视点,电子工业出版社) —— 项目驱动入门,从零写出完整应用
- Keychron K1Max 矮轴机械键盘(Mac/Win 双系统,QMK/VIA 开源改键) —— 轻薄矮轴 + 开源固件,程序员桌面常客
- 罗技 MX Master 3S 无线鼠标(Flow 跨屏,静音电磁滚轮) —— 人体工学设计,写代码一整天手不酸
以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。
📮 关注公众号「GO语言入门之路」
每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。
微信扫码,或搜索「GO语言入门之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。