用 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))
}
如何正确读取 POST 请求的 JSON 数据
很多人卡在 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会自动设置状态码并写入文本,不适合返回结构化错误 JSON
func jsonResponse(w http.ResponseWriter, statusCode int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
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" 处理器(因为是前缀),除非你手动做精确路径判断。
立即学习“go语言免费学习笔记(深入)”;
- 不要依赖注册顺序来“覆盖”路由,
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,标准库适合原型或极简接口,别硬撑嵌套路由或动态参数。










