使用 Go 标准库编写 HTTP 服务
wxk1991 Lv5

使用 Go 标准库编写 HTTP 服务

Go 标准库自带强大的 HTTP 能力。对于很多小型 API、内部服务和健康检查接口,不引入 Web 框架也能写得很清楚。


一、最小服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"fmt"
"net/http"
)

func main() {
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
})

http.ListenAndServe(":8080", nil)
}

访问:

1
curl http://localhost:8080/health

二、返回 JSON

1
2
3
4
5
6
7
8
9
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
}

func userHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(User{ID: 1, Name: "Alice"})
}

三、限制请求方法

1
2
3
4
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}

标准库不会帮你自动约束方法,需要自己处理。


四、配置 Server

生产环境不要直接使用默认 ListenAndServe。建议显式配置超时:

1
2
3
4
5
server := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}

这能避免慢连接长期占用资源。


五、什么时候需要框架

当项目需要路由分组、中间件、参数绑定、OpenAPI 集成时,可以考虑 Gin、Echo、Chi 等框架。否则标准库已经足够可靠。