Go net/http 包详解
概述
net/http 包提供了 HTTP 客户端和服务端的实现。它支持 HTTP/1.x 和 HTTP/2 协议,可用于构建 Web 服务器、API 服务和 HTTP 客户端。包中提供了简单的函数用于发起 HTTP 请求,也提供了高级类型用于精细控制 HTTP 行为。
重要说明:
- ✓ 提供 HTTP 客户端和服务端实现
- ✓ 支持 HTTP/1.x 和 HTTP/2 协议
- ✓ 支持 HTTPS/TLS
- ✓ 支持路由和模式匹配(Go 1.22+ 增强)
- ✓ 支持中间件和自定义处理器
- ✓ 支持连接池和 Keep-Alive
- ✓ Go 1.0+ 引入,Go 1.22+ 路由增强
HTTP/2 支持:
- 自动启用:使用 HTTPS 时自动启用 HTTP/2
- 禁用方法:设置
Transport.TLSNextProto或使用GODEBUG=http2client=0 - 调试模式:
GODEBUG=http2debug=1或GODEBUG=http2debug=2
包导入
import (
"net/http"
)
基本使用
1. HTTP 客户端 GET 请求
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
resp, err := http.Get("https://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %s\n", resp.Status)
fmt.Printf("Body: %s\n", string(body))
}
2. HTTP 服务器
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path)
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server starting on :8080")
http.ListenAndServe(":8080", nil)
}
3. POST 请求
package main
import (
"bytes"
"fmt"
"net/http"
)
func main() {
data := []byte(`{"key": "value"}`)
resp, err := http.Post("https://example.com/api", "application/json", bytes.NewBuffer(data))
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("Status: %d\n", resp.StatusCode)
}
一、常量
HTTP 方法常量
定义:
const (
MethodGet = "GET"
MethodHead = "HEAD"
MethodPost = "POST"
MethodPut = "PUT"
MethodPatch = "PATCH"
MethodDelete = "DELETE"
MethodConnect = "CONNECT"
MethodOptions = "OPTIONS"
MethodTrace = "TRACE"
)
说明:
- MethodGet:GET 请求方法
- MethodHead:HEAD 请求方法
- MethodPost:POST 请求方法
- MethodPut:PUT 请求方法
- MethodPatch:PATCH 请求方法
- MethodDelete:DELETE 请求方法
- MethodConnect:CONNECT 请求方法
- MethodOptions:OPTIONS 请求方法
- MethodTrace:TRACE 请求方法
HTTP 状态码常量
定义:
const (
StatusContinue = 100
StatusSwitchingProtocols = 101
StatusProcessing = 102
StatusEarlyHints = 103
StatusOK = 200
StatusCreated = 201
StatusAccepted = 202
StatusNonAuthoritativeInfo = 203
StatusNoContent = 204
StatusResetContent = 205
StatusPartialContent = 206
StatusMultiStatus = 207
StatusAlreadyReported = 208
StatusIMUsed = 226
StatusMultipleChoices = 300
StatusMovedPermanently = 301
StatusFound = 302
StatusSeeOther = 303
StatusNotModified = 304
StatusUseProxy = 305
StatusTemporaryRedirect = 307
StatusPermanentRedirect = 308
StatusBadRequest = 400
StatusUnauthorized = 401
StatusPaymentRequired = 402
StatusForbidden = 403
StatusNotFound = 404
StatusMethodNotAllowed = 405
StatusNotAcceptable = 406
StatusProxyAuthRequired = 407
StatusRequestTimeout = 408
StatusConflict = 409
StatusGone = 410
StatusLengthRequired = 411
StatusPreconditionFailed = 412
StatusRequestEntityTooLarge = 413
StatusRequestURITooLong = 414
StatusUnsupportedMediaType = 415
StatusRequestedRangeNotSatisfiable = 416
StatusExpectationFailed = 417
StatusTeapot = 418
StatusMisdirectedRequest = 421
StatusUnprocessableEntity = 422
StatusLocked = 423
StatusFailedDependency = 424
StatusTooEarly = 425
StatusUpgradeRequired = 426
StatusPreconditionRequired = 428
StatusTooManyRequests = 429
StatusRequestHeaderFieldsTooLarge = 431
StatusUnavailableForLegalReasons = 451
StatusInternalServerError = 500
StatusNotImplemented = 501
StatusBadGateway = 502
StatusServiceUnavailable = 503
StatusGatewayTimeout = 504
StatusHTTPVersionNotSupported = 505
StatusVariantAlsoNegotiates = 506
StatusInsufficientStorage = 507
StatusLoopDetected = 508
StatusNotExtended = 510
StatusNetworkAuthenticationRequired = 511
)
说明:
- 1xx:信息响应
- 2xx:成功响应
- 3xx:重定向
- 4xx:客户端错误
- 5xx:服务器错误
Cookie 常量
定义:
const (
MaxInt64 = 1<<63 - 1
)
说明:
- 用于 Cookie 过期时间的最大值
二、变量
ErrBodyNotAllowed
定义:
var ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
说明:
- 请求方法或响应状态码不允许包含正文时返回的错误
ErrBodyReadAfterClose
定义:
var ErrBodyReadAfterClose = errors.New("http: read after body closed")
说明:
- 在 Body 关闭后尝试读取时返回的错误
ErrHandlerTimeout
定义:
var ErrHandlerTimeout = errors.New("http: Handler timeout")
说明:
- 处理器超时时返回的错误
ErrLineTooLong
定义:
var ErrLineTooLong = errors.New("http: line too long")
说明:
- HTTP 行太长时返回的错误
ErrMissingFile
定义:
var ErrMissingFile = errors.New("http: no such file")
说明:
- 文件不存在时返回的错误
ErrNoCookie
定义:
var ErrNoCookie = errors.New("http: named cookie not present")
说明:
- 请求中不存在指定名称的 Cookie 时返回的错误
ErrNoLocation
定义:
var ErrNoLocation = errors.New("http: no Location header in response")
说明:
- 响应中没有 Location 头部时返回的错误
ErrSchemeMismatch
定义:
var ErrSchemeMismatch = errors.New("http: server gave HTTP response to HTTPS client")
说明:
- HTTPS 客户端收到 HTTP 响应时返回的错误
ErrServerClosed
定义:
var ErrServerClosed = errors.New("http: Server closed")
说明:
- 服务器已关闭时返回的错误
ErrSkipAltProtocol
定义:
var ErrSkipAltProtocol = errors.New("http: skip alternate protocol")
说明:
- 跳过备用协议时返回的错误
ErrStatementTooLong
定义:
var ErrStatementTooLong = errors.New("http: statement too long")
说明:
- HTTP 语句太长时返回的错误
ErrUnexpectedTrailer
定义:
var ErrUnexpectedTrailer = errors.New("http: unexpected trailer at end of body")
说明:
- 在正文末尾发现意外的 trailer 时返回的错误
DefaultClient
定义:
var DefaultClient = &Client{}
说明:
- 默认的 HTTP 客户端,用于包级别的 Get、Post 等函数
DefaultServeMux
定义:
var DefaultServeMux = &defaultServeMux
说明:
- 默认的 ServeMux,用于包级别的 Handle、HandleFunc 等函数
ErrAbortHandler
定义:
var ErrAbortHandler = errors.New("http: abort Handler")
说明:
- 用于中止处理器而不记录错误
三、函数(按 a-z 排序)
CanonicalHeaderKey
定义:
func CanonicalHeaderKey(s string) string
说明:
- 功能:将头部键转换为规范格式
- 参数:
s- 头部键字符串
- 返回:规范格式的头部键
- 规则:首字母和连字符后的字母大写,其他小写
示例:
package main
import (
"fmt"
"net/http"
)
func main() {
fmt.Println(http.CanonicalHeaderKey("content-type")) // Content-Type
fmt.Println(http.CanonicalHeaderKey("ACCEPT")) // Accept
fmt.Println(http.CanonicalHeaderKey("content-md5")) // Content-Md5
}
运行结果:
Content-Type
Accept
Content-Md5
DetectContentType
定义:
func DetectContentType(data []byte) string
说明:
- 功能:检测数据的 MIME 类型
- 参数:
data- 数据的前 512 字节
- 返回:MIME 类型字符串
示例:
package main
import (
"fmt"
"net/http"
)
func main() {
html := []byte("<!DOCTYPE html><html>")
json := []byte(`{"key": "value"}`)
png := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}
fmt.Println(http.DetectContentType(html)) // text/html; charset=utf-8
fmt.Println(http.DetectContentType(json)) // text/plain; charset=utf-8
fmt.Println(http.DetectContentType(png)) // image/png
}
Error
定义:
func Error(w ResponseWriter, error string, code int)
说明:
- 功能:发送 HTTP 错误响应
- 参数:
w- ResponseWritererror- 错误消息code- HTTP 状态码
- 用途:快速返回错误响应
示例:
func handler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
Handle
定义:
func Handle(pattern string, handler Handler)
说明:
- 功能:向 DefaultServeMux 注册处理器
- 参数:
pattern- URL 模式handler- 处理器
- 用途:注册路由
示例:
http.Handle("/api/", apiHandler)
http.Handle("/static/", staticHandler)
HandleFunc
定义:
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
说明:
- 功能:向 DefaultServeMux 注册处理器函数
- 参数:
pattern- URL 模式handler- 处理器函数
- 用途:快速注册路由
示例:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path)
})
ListenAndServe
定义:
func ListenAndServe(addr string, handler Handler) error
说明:
- 功能:在指定地址启动 HTTP 服务器
- 参数:
addr- 监听地址(如 “:8080”)handler- 处理器(nil 使用 DefaultServeMux)
- 返回:错误信息(总是非 nil)
- 用途:启动 HTTP 服务器
示例:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
})
fmt.Println("Server starting on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
ListenAndServeTLS
定义:
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
说明:
- 功能:在指定地址启动 HTTPS 服务器
- 参数:
addr- 监听地址certFile- 证书文件路径keyFile- 私钥文件路径handler- 处理器
- 返回:错误信息
- 用途:启动 HTTPS 服务器
示例:
err := http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
MaxBytesReader
定义:
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
说明:
- 功能:返回限制读取 n 字节的 ReadCloser
- 参数:
w- ResponseWriterr- 原始 ReadClosern- 最大字节数
- 返回:受限的 ReadCloser
- 用途:防止读取过大的请求体
示例:
func handler(w http.ResponseWriter, r *http.Request) {
// 限制请求体为 1MB
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
return
}
}
NotFound
定义:
func NotFound(w ResponseWriter, r *Request)
说明:
- 功能:发送 404 Not Found 响应
- 参数:
w- ResponseWriterr- Request
- 用途:返回 404 错误
ParseHTTPVersion
定义:
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
说明:
- 功能:解析 HTTP 版本字符串
- 参数:
vers- HTTP 版本字符串(如 “HTTP/1.1”)
- 返回:
major- 主版本号minor- 次版本号ok- 是否解析成功
示例:
major, minor, ok := http.ParseHTTPVersion("HTTP/1.1")
// major=1, minor=1, ok=true
ParseTime
定义:
func ParseTime(text string) (t time.Time, err error)
说明:
- 功能:解析 HTTP 时间格式
- 参数:
text- 时间字符串
- 返回:
time.Time- 解析的时间error- 错误信息
- 支持格式:RFC 1123、RFC 850、ANSIC
ProxyFromEnvironment
定义:
func ProxyFromEnvironment(req *Request) (*url.URL, error)
说明:
- 功能:从环境变量获取代理 URL
- 参数:
req- HTTP 请求
- 返回:
*url.URL- 代理 URLerror- 错误信息
- 环境变量:
HTTP_PROXY、HTTPS_PROXY、NO_PROXY
ProxyURL
定义:
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
说明:
- 功能:返回固定代理的 Proxy 函数
- 参数:
fixedURL- 固定代理 URL
- 返回:Proxy 函数
- 用途:设置固定代理
示例:
proxyURL, _ := url.Parse("http://proxy.example.com:8080")
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
client := &http.Client{Transport: transport}
Redirect
定义:
func Redirect(w ResponseWriter, r *Request, url string, code int)
说明:
- 功能:发送重定向响应
- 参数:
w- ResponseWriterr- Requesturl- 重定向 URLcode- 状态码(301、302、307、308)
- 用途:URL 重定向
示例:
func handler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/new-path", http.StatusMovedPermanently)
}
Serve
定义:
func Serve(l net.Listener, handler Handler) error
说明:
- 功能:从监听器接受连接并服务请求
- 参数:
l- net.Listenerhandler- 处理器
- 返回:错误信息
ServeContent
定义:
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
说明:
- 功能:提供内容服务,支持 Range 请求
- 参数:
w- ResponseWriterreq- Requestname- 文件名modtime- 修改时间content- 内容
- 用途:高效提供文件内容
ServeFile
定义:
func ServeFile(w ResponseWriter, r *Request, name string)
说明:
- 功能:提供文件服务
- 参数:
w- ResponseWriterr- Requestname- 文件路径
- 用途:快速提供文件
示例:
func fileHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/path/to/file.txt")
}
ServeFileFS
定义:
func ServeFileFS(w ResponseWriter, r *http.Request, fsys fs.FS, name string)
说明:
- 功能:从文件系统提供文件服务
- 参数:
w- ResponseWriterr- Requestfsys- 文件系统name- 文件路径
- 版本:Go 1.16+
ServeTLS
定义:
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
说明:
- 功能:从监听器提供 HTTPS 服务
- 参数:
l- net.Listenerhandler- 处理器certFile- 证书文件keyFile- 私钥文件
- 返回:错误信息
SetCookie
定义:
func SetCookie(w ResponseWriter, cookie *Cookie)
说明:
- 功能:设置 Cookie
- 参数:
w- ResponseWritercookie- Cookie 对象
- 用途:添加 Set-Cookie 头部
示例:
cookie := &http.Cookie{
Name: "session",
Value: "abc123",
Path: "/",
}
http.SetCookie(w, cookie)
StatusText
定义:
func StatusText(code int) string
说明:
- 功能:返回状态码的文本描述
- 参数:
code- HTTP 状态码
- 返回:状态文本
示例:
fmt.Println(http.StatusText(200)) // OK
fmt.Println(http.StatusText(404)) // Not Found
fmt.Println(http.StatusText(500)) // Internal Server Error
四、类型(按 a-z 排序)
Client
定义:
type Client struct {
Transport RoundTripper
CheckRedirect func(req *Request, via []*Request) error
Jar CookieJar
Timeout time.Duration
}
说明:
- 功能:HTTP 客户端
- 字段:
Transport- 传输层(默认 DefaultTransport)CheckRedirect- 重定向策略函数Jar- Cookie 管理器Timeout- 请求超时(包括拨号、重定向、读取)
方法:
CloseIdleConnections
定义:
func (c *Client) CloseIdleConnections()
说明:
- 功能:关闭所有空闲连接
- 用途:清理连接池
Do
定义:
func (c *Client) Do(req *Request) (*Response, error)
说明:
- 功能:执行 HTTP 请求
- 参数:
req- HTTP 请求
- 返回:
*Response- HTTP 响应error- 错误信息
- 特点:遵循重定向策略
示例:
package main
import (
"fmt"
"net/http"
)
func main() {
client := &http.Client{
Timeout: 5 * time.Second,
}
req, _ := http.NewRequest("GET", "https://example.com", nil)
req.Header.Set("User-Agent", "MyApp/1.0")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("Status: %s\n", resp.Status)
}
Get
定义:
func (c *Client) Get(url string) (resp *Response, err error)
说明:
- 功能:发送 GET 请求
- 参数:
url- 请求 URL
- 返回:
*Response- HTTP 响应error- 错误信息
Head
定义:
func (c *Client) Head(url string) (resp *Response, err error)
说明:
- 功能:发送 HEAD 请求
- 参数:
url- 请求 URL
- 返回:
*Response- HTTP 响应error- 错误信息
Post
定义:
func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
说明:
- 功能:发送 POST 请求
- 参数:
url- 请求 URLcontentType- Content-Typebody- 请求体
- 返回:
*Response- HTTP 响应error- 错误信息
PostForm
定义:
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
说明:
- 功能:发送表单 POST 请求
- 参数:
url- 请求 URLdata- 表单数据
- 返回:
*Response- HTTP 响应error- 错误信息
CloseNotifier
定义:
type CloseNotifier interface {
CloseNotify() <-chan bool
}
说明:
- 功能:通知客户端连接已关闭
- 已废弃:使用 Request.Context 代替
ConnState
定义:
type ConnState int
说明:
- 功能:连接状态枚举
- 值:
StateNew:新连接StateActive:活跃状态StateIdle:空闲状态StateHijacked:已劫持StateClosed:已关闭
Cookie
定义:
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
RawExpires string
MaxAge int
Secure bool
HttpOnly bool
SameSite SameSite
Raw string
Unparsed []string
}
说明:
- 功能:HTTP Cookie
- 字段:
Name- Cookie 名称Value- Cookie 值Path- 路径Domain- 域名Expires- 过期时间MaxAge- 最大年龄(秒)Secure- 仅 HTTPSHttpOnly- 禁止 JavaScript 访问SameSite- SameSite 策略
CookieJar
定义:
type CookieJar interface {
SetCookies(u *url.URL, cookies []*Cookie)
Cookies(u *url.URL) []*Cookie
}
说明:
- 功能:Cookie 管理器接口
- 实现:
net/http/cookiejar包
Dir
定义:
type Dir string
说明:
- 功能:实现 http.FileSystem 的类型
- 用途:提供本地文件系统访问
File
定义:
type File interface {
io.Closer
io.Reader
Readdir(count int) ([]FileInfo, error)
Stat() (FileInfo, error)
}
说明:
- 功能:http.FileSystem 返回的文件接口
FileSystem
定义:
type FileSystem interface {
Open(name string) (File, error)
}
说明:
- 功能:文件系统接口
- 用途:提供文件访问抽象
Flusher
定义:
type Flusher interface {
Flush()
}
说明:
- 功能:刷新响应缓冲区
- 用途:实现流式响应
Handler
定义:
type Handler interface {
ServeHTTP(w ResponseWriter, r *Request)
}
说明:
- 功能:HTTP 处理器接口
- 用途:处理 HTTP 请求
- 实现者:ServeMux、HandlerFunc 等
示例:
type MyHandler struct{}
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
http.Handle("/", &MyHandler{})
HandlerFunc
定义:
type HandlerFunc func(ResponseWriter, *Request)
说明:
- 功能:适配器类型,将函数转换为 Handler
- 用途:快速实现 Handler 接口
示例:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
http.Handle("/", http.HandlerFunc(handler))
// 或
http.HandleFunc("/", handler)
Header
定义:
type Header map[string][]string
说明:
- 功能:HTTP 头部
- 特点:键是规范化的,值可以有多个
方法:
Add
定义:
func (h Header) Add(key, value string)
说明:
- 功能:添加头部值
- 特点:保留已有值
Del
定义:
func (h Header) Del(key string)
说明:
- 功能:删除头部
Get
定义:
func (h Header) Get(key string) string
说明:
- 功能:获取头部值
- 返回:第一个值或空字符串
Set
定义:
func (h Header) Set(key, value string)
说明:
- 功能:设置头部值
- 特点:替换已有值
Values
定义:
func (h Header) Values(key string) []string
说明:
- 功能:获取头部所有值
Hijacker
定义:
type Hijacker interface {
Hijack() (net.Conn, *bufio.ReadWriter, error)
}
说明:
- 功能:劫持 HTTP 连接
- 用途:WebSocket、HTTP 升级协议
Pusher
定义:
type Pusher interface {
Push(target string, opts *PushOptions) error
}
说明:
- 功能:HTTP/2 Server Push
- 用途:主动推送资源
PushOptions
定义:
type PushOptions struct {
Method string
Header Header
}
说明:
- 功能:Server Push 选项
Request
定义:
type Request struct {
Method string
URL *url.URL
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
GetBody func() (io.ReadCloser, error)
ContentLength int64
TransferEncoding []string
Close bool
Host string
Form url.Values
PostForm url.Values
MultipartForm *multipart.Form
Trailer Header
RemoteAddr string
RequestURI string
TLS *tls.ConnectionState
Cancel <-chan struct{}
Response *Response
Pattern string
ctx context.Context
}
说明:
- 功能:HTTP 请求
- 字段(主要):
Method- 请求方法URL- 请求 URLHeader- 请求头Body- 请求体Form- 解析后的表单PostForm- POST 表单MultipartForm- 多部分表单TLS- TLS 连接信息Pattern- 匹配的路由模式(Go 1.22+)
方法:
AddCookie
定义:
func (r *Request) AddCookie(c *Cookie)
说明:
- 功能:添加 Cookie 到请求
BasicAuth
定义:
func (r *Request) BasicAuth() (username, password string, ok bool)
说明:
- 功能:获取 Basic Auth 凭证
Context
定义:
func (r *Request) Context() context.Context
说明:
- 功能:获取请求上下文
Cookie
定义:
func (r *Request) Cookie(name string) (*Cookie, error)
说明:
- 功能:获取指定 Cookie
Cookies
定义:
func (r *Request) Cookies() []*Cookie
说明:
- 功能:获取所有 Cookie
FormValue
定义:
func (r *Request) FormValue(key string) string
说明:
- 功能:获取表单值
MultipartReader
定义:
func (r *Request) MultipartReader() (*multipart.Reader, error)
说明:
- 功能:获取多部分读取器
ParseForm
定义:
func (r *Request) ParseForm() error
说明:
- 功能:解析表单
ParseMultipartForm
定义:
func (r *Request) ParseMultipartForm(maxMemory int64) error
说明:
- 功能:解析多部分表单
PathValue
定义:
func (r *Request) PathValue(key string) string
说明:
- 功能:获取路径参数值
- 版本:Go 1.22+
示例:
// 路由:/users/{id}
id := r.PathValue("id")
PostFormValue
定义:
func (r *Request) PostFormValue(key string) string
说明:
- 功能:获取 POST 表单值
ProtoAtLeast
定义:
func (r *Request) ProtoAtLeast(major, minor int) bool
说明:
- 功能:检查 HTTP 协议版本
Referer
定义:
func (r *Request) Referer() string
说明:
- 功能:获取 Referer 头部
SetBasicAuth
定义:
func (r *Request) SetBasicAuth(username, password string)
说明:
- 功能:设置 Basic Auth
UserAgent
定义:
func (r *Request) UserAgent() string
说明:
- 功能:获取 User-Agent 头部
WithContext
定义:
func (r *Request) WithContext(ctx context.Context) *Request
说明:
- 功能:创建带上下文的请求副本
Response
定义:
type Response struct {
Status string
StatusCode int
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
ContentLength int64
TransferEncoding []string
Close bool
Uncompressed bool
Trailer Header
Request *Request
TLS *tls.ConnectionState
}
说明:
- 功能:HTTP 响应
- 字段:
Status- 状态文本StatusCode- 状态码Header- 响应头Body- 响应体ContentLength- 内容长度TLS- TLS 连接信息
方法:
Cookies
定义:
func (r *Response) Cookies() []*Cookie
说明:
- 功能:获取响应中的 Cookie
Location
定义:
func (r *Response) Location() (*url.URL, error)
说明:
- 功能:获取 Location 头部
ResponseWriter
定义:
type ResponseWriter interface {
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}
说明:
- 功能:HTTP 响应写入器接口
- 用途:构建和发送 HTTP 响应
RoundTripper
定义:
type RoundTripper interface {
RoundTrip(*Request) (*Response, error)
}
说明:
- 功能:HTTP 传输接口
- 实现:Transport
SameSite
定义:
type SameSite int
说明:
- 功能:Cookie SameSite 策略
- 值:
SameSiteDefaultModeSameSiteLaxModeSameSiteStrictModeSameSiteNoneMode
ServeMux
定义:
type ServeMux struct {
// 未导出字段
}
说明:
- 功能:HTTP 请求多路复用器
- 用途:路由分发
方法:
Handle
定义:
func (mux *ServeMux) Handle(pattern string, handler Handler)
说明:
- 功能:注册处理器
HandleFunc
定义:
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
说明:
- 功能:注册处理器函数
Handler
定义:
func (mux *ServeMux) Handler(r *Request) (Handler, string)
说明:
- 功能:获取匹配的处理器
ServeHTTP
定义:
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
说明:
- 功能:实现 Handler 接口
Server
定义:
type Server struct {
Addr string
Handler Handler
DisableGeneralOptionsHandler bool
TLSConfig *tls.Config
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
ConnState func(net.Conn, ConnState)
ErrorLog *log.Logger
BaseContext func(net.Listener) context.Context
ConnContext func(ctx context.Context, c net.Conn) context.Context
Protocols *Protocols
HTTP2 *HTTP2Config
inShutdown atomic.Bool
disableKeepAlives atomic.Bool
onStop []func()
mu sync.Mutex
listeners map[net.Listener]struct{}
activeConn map[*conn]struct{}
onShutdown []func()
protoOnce sync.Once
protoHandler Handler
}
说明:
- 功能:HTTP 服务器
- 字段(主要):
Addr- 监听地址Handler- 处理器ReadTimeout- 读取超时WriteTimeout- 写入超时IdleTimeout- 空闲超时MaxHeaderBytes- 最大头部字节数TLSConfig- TLS 配置
方法:
Close
定义:
func (s *Server) Close() error
说明:
- 功能:关闭服务器
ListenAndServe
定义:
func (s *Server) ListenAndServe() error
说明:
- 功能:启动 HTTP 服务器
ListenAndServeTLS
定义:
func (s *Server) ListenAndServeTLS(certFile, keyFile string) error
说明:
- 功能:启动 HTTPS 服务器
RegisterOnShutdown
定义:
func (s *Server) RegisterOnShutdown(f func())
说明:
- 功能:注册关闭回调
Serve
定义:
func (s *Server) Serve(l net.Listener) error
说明:
- 功能:从监听器提供服务
ServeTLS
定义:
func (s *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
说明:
- 功能:从监听器提供 HTTPS 服务
Shutdown
定义:
func (s *Server) Shutdown(ctx context.Context) error
说明:
- 功能:优雅关闭服务器
- 参数:
ctx- 上下文(控制超时)
- 用途:等待活跃连接完成
示例:
srv := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
// 优雅关闭
go func() {
<-shutdownChan
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
}()
srv.ListenAndServe()
Transport
定义:
type Transport struct {
Proxy func(*Request) (*url.URL, error)
DialContext func(context.Context, string, string) (net.Conn, error)
DialTLSContext func(context.Context, string, string) (net.Conn, error)
ForceAttemptHTTP2 bool
MaxIdleConns int
MaxIdleConnsPerHost int
MaxConnsPerHost int
IdleConnTimeout time.Duration
TLSHandshakeTimeout time.Duration
ResponseHeaderTimeout time.Duration
ExpectContinueTimeout time.Duration
TLSClientConfig *tls.Config
TLSNextProto map[string]func(string, *tls.Conn) RoundTripper
ProxyConnectHeader Header
GetProxyConnectHeader func(context.Context, *url.URL) (Header, error)
MaxResponseHeaderBytes int64
WriteBufferSize int
ReadBufferSize int
Protocols *Protocols
HTTP2 *HTTP2Config
}
说明:
- 功能:HTTP 传输层
- 字段(主要):
Proxy- 代理函数DialContext- 拨号函数MaxIdleConns- 最大空闲连接数MaxIdleConnsPerHost- 每个主机最大空闲连接IdleConnTimeout- 空闲连接超时TLSClientConfig- TLS 配置ResponseHeaderTimeout- 响应头部超时
方法:
CancelRequest
定义:
func (t *Transport) CancelRequest(req *Request)
说明:
- 功能:取消请求(已废弃,使用 Context)
CloseIdleConnections
定义:
func (t *Transport) CloseIdleConnections()
说明:
- 功能:关闭所有空闲连接
RoundTrip
定义:
func (t *Transport) RoundTrip(req *Request) (*Response, error)
说明:
- 功能:执行 HTTP 请求
- 实现:RoundTripper 接口
五、典型示例
示例 1:RESTful API 服务器
package main
import (
"encoding/json"
"net/http"
"sync"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
var (
users = make(map[int]User)
nextID = 1
mu sync.RWMutex
)
func listUsers(w http.ResponseWriter, r *http.Request) {
mu.RLock()
defer mu.RUnlock()
userList := make([]User, 0, len(users))
for _, user := range users {
userList = append(userList, user)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userList)
}
func createUser(w http.ResponseWriter, r *http.Request) {
var user User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mu.Lock()
user.ID = nextID
nextID++
users[user.ID] = user
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)
}
func getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
mu.RLock()
defer mu.RUnlock()
// 简化实现
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"id": 1, "name": "John"}`))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /users", listUsers)
mux.HandleFunc("POST /users", createUser)
mux.HandleFunc("GET /users/{id}", getUser)
http.ListenAndServe(":8080", mux)
}
示例 2:HTTP 客户端带重试
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func getWithRetry(url string, maxRetries int) (*http.Response, error) {
client := &http.Client{
Timeout: 5 * time.Second,
}
var resp *http.Response
var err error
for i := 0; i < maxRetries; i++ {
resp, err = client.Get(url)
if err == nil && resp.StatusCode < 500 {
return resp, nil
}
time.Sleep(time.Duration(i+1) * time.Second)
}
return resp, err
}
func main() {
resp, err := getWithRetry("https://example.com", 3)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %s\n", resp.Status)
fmt.Printf("Body: %s\n", string(body))
}
示例 3:中间件实现
package main
import (
"log"
"net/http"
"time"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// 调用下一个处理器
next.ServeHTTP(w, r)
// 记录日志
log.Printf(
"%s %s %s %v",
r.RemoteAddr,
r.Method,
r.URL.Path,
time.Since(start),
)
})
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token != "secret" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello!"))
})
// 应用中间件
handler := loggingMiddleware(authMiddleware(mux))
http.ListenAndServe(":8080", handler)
}
示例 4:文件上传
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 限制上传大小为 10MB
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
// 解析 multipart 表单
err := r.ParseMultipartForm(10 << 20)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 获取文件
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// 创建目标文件
dst, err := os.Create("./uploads/" + header.Filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
// 复制内容
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "File uploaded successfully: %s", header.Filename)
}
func main() {
http.HandleFunc("/upload", uploadHandler)
http.ListenAndServe(":8080", nil)
}
示例 5:JSON API
package main
import (
"encoding/json"
"net/http"
)
type Response struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
func jsonHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
response := Response{
Success: true,
Data: map[string]string{"message": "Hello"},
}
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/api", jsonHandler)
http.ListenAndServe(":8080", nil)
}
示例 6:HTTPS 服务器
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello over HTTPS!")
})
// 需要证书文件
err := http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
if err != nil {
panic(err)
}
}
示例 7:流式响应
package main
import (
"fmt"
"net/http"
"time"
)
func streamHandler(w http.ResponseWriter, r *http.Request) {
// 获取 Flusher
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming not supported", http.StatusInternalServerError)
return
}
// 设置流式头部
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// 流式发送数据
for i := 1; i <= 5; i++ {
fmt.Fprintf(w, "Message %d\n", i)
flusher.Flush()
time.Sleep(1 * time.Second)
}
}
func main() {
http.HandleFunc("/stream", streamHandler)
http.ListenAndServe(":8080", nil)
}
示例 8:优雅关闭
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
// 优雅关闭
go func() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
fmt.Println("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
fmt.Printf("Server shutdown error: %v\n", err)
}
}()
fmt.Println("Server starting on :8080")
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}
六、最佳实践
1. 重用 Client 和 Transport
// ✓ 正确:创建一次,重复使用
var httpClient = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
},
}
// ✗ 错误:每次请求都创建新客户端
resp, err := (&http.Client{}).Get(url)
2. 始终关闭 Response Body
// ✓ 正确:使用 defer 关闭
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// ✗ 错误:忘记关闭
resp, err := http.Get(url)
body, _ := io.ReadAll(resp.Body) // 资源泄漏
3. 设置超时
// ✓ 正确:设置超时
client := &http.Client{
Timeout: 30 * time.Second,
}
// ✗ 错误:没有超时
client := &http.Client{}
4. 检查错误
// ✓ 正确:检查所有错误
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status: %s", resp.Status)
}
// ✗ 错误:忽略错误
resp, _ := http.Get(url)
5. 使用 Context 控制请求
// ✓ 正确:使用 Context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := client.Do(req)
// ✗ 错误:无法取消
resp, err := http.Get(url)
6. 自定义路由
// ✓ 正确:使用自定义 ServeMux
mux := http.NewServeMux()
mux.HandleFunc("/api/", apiHandler)
mux.HandleFunc("/static/", staticHandler)
http.ListenAndServe(":8080", mux)
// ✗ 错误:使用 DefaultServeMux(可能冲突)
http.HandleFunc("/", handler)
7. 设置服务器超时
// ✓ 正确:设置超时
srv := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
// ✗ 错误:没有超时
http.ListenAndServe(":8080", nil)
8. 优雅关闭
// ✓ 正确:优雅关闭
srv.Shutdown(ctx)
// ✗ 错误:强制关闭
srv.Close()
七、与其他包配合
1. 与 context 配合
import (
"context"
"net/http"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
select {
case <-ctx.Done():
http.Error(w, "timeout", http.StatusRequestTimeout)
return
case <-time.After(2 * time.Second):
w.Write([]byte("Done"))
}
}
2. 与 encoding/json 配合
import (
"encoding/json"
"net/http"
)
type User struct {
Name string `json:"name"`
}
func handler(w http.ResponseWriter, r *http.Request) {
var user User
json.NewDecoder(r.Body).Decode(&user)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
3. 与 io 配合
import (
"io"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
// 限制读取
limited := io.LimitReader(r.Body, 1024)
data, _ := io.ReadAll(limited)
// 流式复制
io.Copy(w, r.Body)
}
4. 与 net/http/httptest 配合
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected 200, got %d", w.Code)
}
}
八、快速参考
函数速查
| 函数 | 功能 | 返回 |
|---|---|---|
Get(url) | GET 请求 | *Response, error |
Post(url, type, body) | POST 请求 | *Response, error |
Head(url) | HEAD 请求 | *Response, error |
Handle(pattern, handler) | 注册处理器 | - |
HandleFunc(pattern, fn) | 注册处理器函数 | - |
ListenAndServe(addr, h) | 启动 HTTP 服务器 | error |
ListenAndServeTLS(...) | 启动 HTTPS 服务器 | error |
Redirect(w, r, url, code) | 重定向 | - |
Error(w, msg, code) | 错误响应 | - |
ServeFile(w, r, name) | 提供文件 | - |
SetCookie(w, cookie) | 设置 Cookie | - |
StatusText(code) | 状态文本 | string |
类型速查
| 类型 | 功能 |
|---|---|
Client | HTTP 客户端 |
Transport | 传输层 |
Request | HTTP 请求 |
Response | HTTP 响应 |
ResponseWriter | 响应写入器 |
Handler | 处理器接口 |
HandlerFunc | 处理器函数适配器 |
ServeMux | 路由复用器 |
Server | HTTP 服务器 |
Cookie | HTTP Cookie |
Header | HTTP 头部 |
HTTP 方法
| 方法 | 用途 |
|---|---|
| GET | 获取资源 |
| POST | 创建资源 |
| PUT | 更新资源 |
| DELETE | 删除资源 |
| PATCH | 部分更新 |
| HEAD | 获取头部 |
| OPTIONS | 获取支持的方法 |
状态码分类
| 范围 | 含义 |
|---|---|
| 1xx | 信息 |
| 2xx | 成功 |
| 3xx | 重定向 |
| 4xx | 客户端错误 |
| 5xx | 服务器错误 |
九、注意事项
1. 必须关闭 Body
// Body 必须关闭,否则资源泄漏
resp, _ := http.Get(url)
defer resp.Body.Close() // ✓ 必须
2. Client 并发安全
// Client 和 Transport 是并发安全的
// 应该创建一次,重复使用
var client = &http.Client{Timeout: 30 * time.Second}
3. 默认超时
// DefaultClient 没有超时
// 应该创建自定义 Client
client := &http.Client{Timeout: 30 * time.Second}
4. 重定向策略
// 默认跟随最多 10 次重定向
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return fmt.Errorf("too many redirects")
}
return nil
},
}
5. 路径参数(Go 1.22+)
// Go 1.22+ 支持路径参数
http.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
})
// 旧版本需要手动解析
6. 方法匹配(Go 1.22+)
// Go 1.22+ 支持方法匹配
http.HandleFunc("GET /users", listUsers)
http.HandleFunc("POST /users", createUser)
// 旧版本需要手动检查
if r.Method == http.MethodGet {
// ...
}
7. 头部规范化
// 头部键自动规范化
header.Set("content-type", "application/json")
fmt.Println(header.Get("Content-Type")) // application/json
8. 平台差异
// Windows: 证书存储位置不同
// Unix: 从系统证书存储读取
// 跨平台应用需要处理证书验证
最后更新: 2026-04-05
Go 版本: Go 1.0+(Go 1.22+ 路由增强)
包文档: https://pkg.go.dev/net/http
相关 RFC: RFC 7230-7235 (HTTP/1.1), RFC 7540 (HTTP/2)