Go http包
Go标准库net/http提供完整的HTTP客户端和服务端功能。
HTTP服务端
基本服务器
Go
import "net/http"
func main() {
// 注册路由
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
})
// 启动服务
http.ListenAndServe(":8080", nil)
}
HandleFunc注册路由
Go
// 注册处理函数
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/user", userHandler)
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
}
func userHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("User"))
}
http.Request请求对象
Go
func handler(w http.ResponseWriter, r *http.Request) {
// 请求方法
method := r.Method // GET, POST, PUT, DELETE
// 请求路径
path := r.URL.Path
// 查询参数
query := r.URL.Query()
name := query.Get("name")
// 请求头
contentType := r.Header.Get("Content-Type")
// 请求体
body, _ := io.ReadAll(r.Body)
defer r.Body.Close()
}
http.ResponseWriter响应对象
Go
func handler(w http.ResponseWriter, r *http.Request) {
// 设置响应头
w.Header().Set("Content-Type", "application/json")
// 设置状态码
w.WriteHeader(http.StatusOK)
// 写入响应体
w.Write([]byte(`{"status":"ok"}`))
}
// 注意:WriteHeader必须在Write之前调用
HTTP客户端
http.Get请求
Go
// 简单GET请求
resp, err := http.Get("https://api.example.com/data")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// 读取响应
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
// 状态码
fmt.Println(resp.StatusCode)
http.Post请求
Go
// POST请求
resp, err := http.Post(
"https://api.example.com/create",
"application/json",
bytes.NewBuffer([]byte(`{"name":"test"}`)),
)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
自定义请求
Go
// 创建请求对象
req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
// 设置请求头
req.Header.Set("Authorization", "Bearer token")
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
超时设置
Go
// 带超时的客户端
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, _ := client.Get("https://api.example.com/data")
http.Server配置
自定义服务器
Go
server := &http.Server{
Addr: ":8080",
Handler: nil, // 使用DefaultServeMux
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
server.ListenAndServe()
使用路由器
Go
// 自定义路由器
mux := http.NewServeMux()
mux.HandleFunc("/", homeHandler)
mux.HandleFunc("/api", apiHandler)
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
server.ListenAndServe()
中间件模式
基本中间件
Go
// 日志中间件
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))
})
}
// 使用中间件
handler := loggingMiddleware(http.HandlerFunc(homeHandler))
http.Handle("/", handler)
链式中间件
Go
// 多个中间件
func chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
for _, m := range middlewares {
h = m(h)
}
return h
}
handler := chain(
http.HandlerFunc(homeHandler),
loggingMiddleware,
authMiddleware,
)
常用状态码
Go
const (
StatusOK = 200
StatusCreated = 201
StatusBadRequest = 400
StatusUnauthorized = 401
StatusForbidden = 403
StatusNotFound = 404
StatusInternalServerError = 500
)
// 使用
w.WriteHeader(http.StatusOK)
w.WriteHeader(http.StatusNotFound)
HTTP方法表
| 方法 | 用途 | 示例 |
|---|---|---|
| GET | 获取资源 | http.Get() |
| POST | 创建资源 | http.Post() |
| PUT | 更新资源 | NewRequest + Do |
| DELETE | 删除资源 | NewRequest + Do |
静态文件服务
Go
// 文件服务器
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// 访问:http://localhost:8080/static/file.txt
JSON响应处理
Go
func jsonHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
data := map[string]string{"message": "hello"}
json.NewEncoder(w).Encode(data)
}
// JSON请求解析
func createHandler(w http.ResponseWriter, r *http.Request) {
var data struct {
Name string `json:"name"`
}
json.NewDecoder(r.Body).Decode(&data)
}
优雅关闭
Go
server := &http.Server{Addr: ":8080"}
go func() {
server.ListenAndServe()
}()
// 监听信号
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
// 优雅关闭
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
server.Shutdown(ctx)
要点总结
- http.HandleFunc注册路由处理函数
- http.Request包含请求信息
- http.ResponseWriter写入响应
- http.Get/Post发送简单请求
- http.NewRequest创建自定义请求
- http.Client配置超时等参数
- 中间件模式实现横切关注点
- http.Server自定义服务器配置
- 静态文件用http.FileServer
- 优雅关闭使用Shutdown方法
📝 发现内容有误?点击此处直接编辑