Go 的 net/http 包内置轻量,几行代码即可启动 Web 服务器;通过 http.HandleFunc 注册处理器,用 http.ListenAndServe 监听端口;请求参数可从 r.URL.Query()、r.FormValue() 或 json.NewDecoder(r.Body) 获取;响应需用 w.WriteHeader() 设状态码、w.Header().Set() 设头;路由可用默认 ServeMux 或 gorilla/mux 等第三方库;中间件通过包装 http.Handler 实现。

用 Go 的 net/http 包构建 Web 服务器非常直接——它内置、轻量、无需额外依赖,几行代码就能跑起一个可工作的服务。
Go 标准库的 http.ListenAndServe 是入口。它监听指定地址(如 :8080),并把请求分发给注册的处理器(Handler)。
http.HandleFunc 注册路径和处理函数func(http.ResponseWriter, *http.Request) 签名ResponseWriter 用于写响应头和响应体;*http.Request 提供请求方法、URL、Header、Body 等信息示例:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}运行后访问 http://localhost:8080/hello 即可看到响应。
立即学习“go语言免费学习笔记(深入)”;
常见需求包括获取 URL 查询参数、表单数据、JSON 请求体等,*http.Request 提供了对应方法:
r.URL.Query().Get("key"):获取 query string 参数(如 /search?q=go 中的 q)r.FormValue("name"):自动解析 application/x-www-form-urlencoded 或 multipart/form-data 表单字段(会隐式调用 ParseForm)json.NewDecoder(r.Body).Decode(&data):读取 JSON 请求体(注意:r.Body 只能读一次,需提前检查 Content-Type)小提示:如果同时需要 query 和 form 数据,建议显式调用 r.ParseForm(),再统一从 r.Form 取值。
默认响应状态是 200 OK,但实际开发中常需自定义:
w.WriteHeader(http.StatusNotFound) 设置非 200 状态码(必须在写入响应体前调用)w.Header().Set("Content-Type", "application/json; charset=utf-8") 设置响应头Content-Type 并用 json.NewEncoder(w).Encode(data) 安全输出错误响应示例:
func apiHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("Only POST allowed"))
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}http.DefaultServeMux 是默认的多路复用器,支持前缀匹配(如 /api/)和精确路径匹配,但不支持动态路径(如 /user/:id)。
http.ServeMux 实例,避免污染全局默认 muxgorilla/mux 或 chi,它们仍基于 net/http 接口,无缝兼容http.Handler 接口,因此可自由组合中间件(如日志、CORS、认证)例如加个简单日志中间件:
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("→ %s %s\n", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", loggingMiddleware(mux))
}net/http 足够支撑中小型 API 和静态服务,理解其 Handler 模型和生命周期是写出健壮服务的关键。不复杂但容易忽略细节。
以上就是如何使用Golang构建Web服务器_使用net/http处理请求和响应的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号