用 net/http 启动基础 HTTP 服务需调用 http.HandleFunc 注册处理器、http.ListenAndServe 启动并用 log.Fatal 处理启动错误;路径匹配为前缀匹配,端口冲突需手动排查。
net/http 启动一个基础 HTTP 服务Go 自带的 net/http 包足够轻量,不需要额外依赖就能跑起一个服务。关键不是“怎么写”,而是别漏掉 http.ListenAndServe 的错误处理——它只在启动失败时返回错误,成功后会阻塞运行,所以必须用 log.Fatal 或显式判断。
http.HandleFunc 注册路径处理器,第一个参数是路径前缀(比如 "/api"),第二个是函数类型 func(http.ResponseWriter, *http.Request)
"/" 会捕获所有未被更长前缀覆盖的请求"listen tcp :8080: bind: address already in use",需手动检查或换端口package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
很多人卡在 r.Body 读不到内容,本质是没调用 r.ParseForm() 或 json.NewDecoder(r.Body).Decode() 前忘了 defer r.Body.Close(),或者 Content-Type 不匹配导致解析失败。
Content-Type: application/json,否则 json.Decode 可能静默失败r.Body 是 io.ReadCloser,不关闭会导致连接复用异常、内存泄漏r.FormValue 或 r.ParseForm(),r.Body 已被读过,再读就是空json.NewDecoder(r.Body).Decode(&v),比 io.ReadAll + json.Unmarshal 更省内存type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
func handleUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var u User
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
defer r.Body.Close()
fmt.Printf("Received: %+v\n", u)
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
http.ResponseWriter 不是“写完就完”,它的 Header() 方法必须在 Write 或 WriteHeader 调用前设置,否则会被忽略。常见坑是:先 w.Write 再设 Content-Type,结果浏览器收到的是默认 text/plain。
w.WriteHeader(statusCode) 显式设置,否则默认是 200 OK
w.Header().Set("Content-Type", "application/json") 要在任何 w.Write 之前json.NewEncoder(w).Encode(map[string]string{...})
http.Error 会自动设置状态码并写入文本,不适合返回结构化错误 JSONfunc jsonResponse(w http.ResponseWriter, statusCode int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(sta
tusCode)
json.NewEncoder(w).Encode(payload)
}
// 使用示例:
jsonResponse(w, http.StatusNotFound, map[string]string{"error": "user not found"})
Go 标准库没有内置路由树或中间件链,http.ServeMux 是简单前缀匹配,注册顺序无关,但匹配逻辑容易误判。比如 "/users" 和 "/users/profile" 都注册了,"/users/profile" 请求会命中 "/users" 处理器(因为是前缀),除非你手动做精确路径判断。
ServeMux 不支持优先级next.ServeHTTP(w, r),漏掉这句请求就停在那里,无响应也无错误r.Header 或 r.URL 是安全的,但改 w.Header() 必须在 w.Write 前log.Printf("path: %s, method: %s", r.URL.Path, r.Method) 确认是否走到预期逻辑真正复杂路由建议直接上 gorilla/mux 或 chi,标准库适合原型或极简接口,别硬撑嵌套路由或动态参数。