Golang Web 编程:net/http 快速上手

前言 标准库 net/http 就能写出生产级 Web 服务。这篇从路由到优雅关停走一遍,再聊什么时候需要框架。 一、五分钟起步 package main import ( "encoding/json" "log" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "ok") }) // JSON API mux.HandleFunc("GET /api/users/{id}", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") // go1.22+ 原生路径参数! json.NewEncoder(w).Encode(map[string]string{ "id": id, "name": "zy", }) }) log.Println("listening :8080") log.Fatal(http.ListenAndServe(":8080", mux)) } curl http://localhost:8080/healthz curl http://localhost:8080/api/users/42 Go 1.22 后 ServeMux 支持方法限定 + 路径参数(GET /users/{id}),日常路由基本不用框架了。 ...

2025-01-18 · 2 min · zy