HTTP(HyperText Transfer Protocol,超文本传输协议)是互联网上应用最为广泛的一种网络协议,用于客户端和服务器之间的通信。
核心特点:
客户端 (浏览器/APP) 服务器 (Web服务)
| |
| --- HTTP请求 -------> |
| |
| <--- HTTP响应 -------- |
| |
GET /api/students HTTP/1.1 ← 请求行(方法 + URL + 协议版本)
Host: localhost:8080 ← 请求头(元数据)
Content-Type: application/json
Authorization: Bearer token123
← 空行分隔
{"name": "张三", "age": 20} ← 请求体(可选,POST/PUT时有)
HTTP方法语义:
GET:获取资源(查)POST:创建资源(增)PUT:更新资源(改)DELETE:删除资源(删)PATCH:部分更新HTTP/1.1 200 OK ← 状态行(协议版本 + 状态码 + 描述)
Content-Type: application/json ← 响应头(元数据)
Content-Length: 45
Date: Mon, 23 Oct 2023 08:00:00 GMT
← 空行分隔
{"id": 1, "name": "张三", "age": 20} ← 响应体(数据内容)
常见状态码:
200 OK:请求成功201 Created:资源创建成功400 Bad Request:客户端请求错误401 Unauthorized:未认证404 Not Found:资源不存在500 Internal Server Error:服务器内部错误客户端请求
↓
http.ServeMux (路由 multiplexer)
↓
http.Handler (处理器接口)
↓
具体处理逻辑 (HandlerFunc或自定义Handler)
↓
http.ResponseWriter (写回响应)
1. 路由 (ServeMux)
2. 处理器 (Handler)
// Handler是一个接口,只需要实现一个方法
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
3. 处理器函数 (HandlerFunc)
// 函数签名,与ServeHTTP方法相同
type HandlerFunc func(ResponseWriter, *Request)
4. 请求对象 (Request)
5. 响应写入器 (ResponseWriter)
步骤1:设计API端点
GET /students # 获取所有学生
POST /students body=json # 创建新学生
GET /students?id=1 # 获取特定学生
PUT /students body=json # 更新学生信息
DELETE /students body=json # 删除学生
步骤2:定义处理器函数
func getStudents(w http.ResponseWriter, r *http.Request) {
// 处理GET /students 请求
}
func createStudent(w http.ResponseWriter, r *http.Request) {
// 处理POST /students 请求
}
步骤3:注册路由
mux := http.NewServeMux()
mux.HandleFunc("/students", studentsHandler) // 处理/students路径
步骤4:启动服务器
// 监听8080端口,使用自定义路由
http.ListenAndServe(":8080", mux)
package main
import (
"fmt"
"net/http"
)
// 处理器函数:处理健康检查
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"status": "healthy", "service": "student-api"}`)
}
func getStudentsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodGet {
fmt.Fprintf(w, `[{"id": 1, "name": "张三", "age": 20}]`)
return
}
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
func main() {
// 创建路由
mux := http.NewServeMux()
// 注册路由路径和对应的处理器函数
mux.HandleFunc("/students", getStudentsHandler)
mux.HandleFunc("/health", healthHandler)
// 启动服务器
fmt.Println("服务器启动在 http://localhost:8080")
fmt.Println("健康检查: http://localhost:8080/health")
err := http.ListenAndServe(":8080", mux)
if err != nil {
fmt.Printf("服务器启动失败: %v\n", err)
}
}
中间件是在请求到达具体处理器之前或之后执行的一些通用逻辑:
// 日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("收到请求: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r) // 调用下一个处理器
})
}
// 使用中间件
handler := loggingMiddleware(mux)
http.ListenAndServe(":8080", handler)