在 Go 语言中,如果你要开发 Web 服务、API 接口、HTTP 客户端,那么最核心的标准库就是
net/http。它不仅提供了完整的 HTTP 协议实现,还内置了服务器和客户端能力,可以说:不用任何第三方框架,就可以构建生产级 Web 服务。
net/http 的设计理念非常简单:基于接口、组合优先、开箱即用。这也是为什么很多 Go Web 框架(如 Gin、Echo)本质上都是对它的封装。
一、最简单的 HTTP 服务
Go 提供了非常简洁的方式来启动一个 Web 服务:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Go HTTP")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
运行后访问:
http://localhost:8080
浏览器会显示:
Hello Go HTTP
这里有几个核心点:
HandleFunc注册路由ResponseWriter用于返回响应Request表示请求数据ListenAndServe启动服务器
二、Handler 机制
Go 的 HTTP 核心是 Handler 接口:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
也就是说,只要实现了 ServeHTTP 方法,就可以处理 HTTP 请求。
type MyHandler struct{}
func (h MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("custom handler"))
}
func main() {
http.Handle("/", MyHandler{})
http.ListenAndServe(":8080", nil)
}
这种设计让代码更加灵活,可以实现中间件、路由系统等。
三、请求处理
http.Request 包含所有请求信息:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Method:", r.Method)
fmt.Println("URL:", r.URL.Path)
fmt.Println("Query:", r.URL.Query())
}
获取 GET 参数:
name := r.URL.Query().Get("name")
处理 POST 表单:
r.ParseForm()
username := r.FormValue("username")
读取请求体:
body, _ := io.ReadAll(r.Body)
四、返回响应
通过 ResponseWriter 可以控制响应内容:
w.Write([]byte("hello"))
设置响应头:
w.Header().Set("Content-Type", "application/json")
设置状态码:
w.WriteHeader(http.StatusOK)
返回 JSON:
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"msg":"ok"}`))
五、路由控制
Go 默认路由比较简单:
http.HandleFunc("/user", userHandler)
http.HandleFunc("/order", orderHandler)
匹配规则:
- 精确匹配优先
- 支持前缀匹配
例如:
http.HandleFunc("/api/", apiHandler)
可以匹配:
/api/user
/api/order
六、中间件机制
虽然 net/http 没有内置中间件,但可以很容易实现。
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("request:", r.URL.Path)
next.ServeHTTP(w, r)
})
}
使用:
http.Handle("/", logging(http.HandlerFunc(handler)))
常见中间件:
日志 鉴权 限流 跨域处理
七、HTTP 客户端
除了服务端,net/http 还可以发送请求。
最简单的 GET 请求:
resp, err := http.Get("https://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
POST 请求:
resp, _ := http.Post(
"https://example.com",
"application/json",
strings.NewReader(`{"name":"test"}`),
)
八、自定义 Client
可以自定义 HTTP 客户端配置:
client := &http.Client{
Timeout: 5 * time.Second,
}
resp, _ := client.Get("https://example.com")
适用于:
超时控制 连接复用 代理设置
九、文件服务
Go 可以快速实现文件服务器:
http.Handle("/", http.FileServer(http.Dir("./static")))
访问:
http://localhost:8080/index.html
适用于:
静态资源服务 下载服务器
十、JSON API 实战
一个简单 API 示例:
func apiHandler(w http.ResponseWriter, r *http.Request) {
type Resp struct {
Message string `json:"message"`
}
res := Resp{Message: "success"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
十一、并发模型
Go 的 HTTP 服务默认是并发的,每个请求都会分配一个 goroutine。这意味着:
- 不需要手动开启并发
- 天然支持高并发
但需要注意:
共享数据必须加锁(sync)
十二、实际应用场景
net/http 广泛用于:
Web API 服务 微服务架构 文件上传下载系统 爬虫客户端 代理服务器 Webhook 服务
例如你做的:
PDF 工具服务 Excel 处理 API 图片处理服务
都可以直接基于 net/http 构建。
总结
net/http 是 Go 语言中最核心的 Web 开发库,它提供了完整的 HTTP 服务端与客户端能力,并且设计简单、性能优秀。
核心能力包括:
HTTP 服务(HandleFunc / Handler) 请求处理(Request) 响应控制(ResponseWriter) 客户端请求(http.Client) 中间件机制 文件服务
相比其他语言,Go 不依赖复杂框架,仅使用标准库就可以构建高性能 Web 服务。
如果你正在开发:
API 服务 工具类后端 文件处理系统 自动化服务
那么 net/http 完全可以作为你的核心基础设施。