Go语言的net/http
标准库提供了构建HTTP服务器和客户端的基础设施。以下是一些常用方法的总结:
HTTP服务器相关
- http.ListenAndServe:启动一个HTTP服务器并监听指定的地址和端口。
err := http.ListenAndServe(":8080", nil)
- http.HandleFunc:将一个HTTP路由映射到一个处理器函数。
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})
- http.ServeFile:使用HTTP响应来服务一个文件。
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
- http.FileServer:返回一个可以提供目录文件服务的
http.Handler
。
http.Handle("/", http.FileServer(http.Dir("./static")))
- http.ServeMux:一个ServeMux用于多路复用HTTP请求到不同的处理器。
mux := http.NewServeMux()
mux.HandleFunc("/", HomeHandler)
mux.HandleFunc("/about", AboutHandler)
- http.ResponseWriter:一个接口,用于写入HTTP响应。
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Hello, World!"))
HTTP客户端相关
- http.Get:执行一个简单的HTTP GET请求。
resp, err := http.Get("http://example.com")
- http.Post:执行一个HTTP POST请求。
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
- http.NewRequest:创建一个新的HTTP请求。
req, err := http.NewRequest("GET", "http://example.com", nil)
- http.Client:执行一个HTTP请求,并返回一个
http.Response
。
client := &http.Client{}
resp, err := client.Do(req)
- http.Client.Post:使用
http.Client
执行一个POST请求。
resp, err := client.Post("http://example.com/upload", "application/json", bytes.NewBuffer(data))
- http.Client.Do:执行一个给定的HTTP请求,并返回一个
http.Response
。
resp, err := client.Do(req)
- http.ReadResponse:从
io.Reader
读取并解析HTTP响应。
resp, err := http.ReadResponse(bufio.NewReader(reader), req)
其他常用功能
- http.ParseHTTPVersion:解析HTTP版本字符串。
major, minor, err := http.ParseHTTPVersion("HTTP/1.1")
- http.StatusText:返回HTTP状态码对应的文本。
text := http.StatusText(404)
- http.DetectContentType:根据提供的块数据来检测MIME类型。
contentType := http.DetectContentType(data)
- http.Cookie:表示一个HTTP cookie,并实现了
encoding.TextMarshaler
和encoding.TextUnmarshaler
接口。
cookie := &http.Cookie{Name: "name", Value: "value"}
- http.SetCookie:写入一个cookie到HTTP响应头中。
http.SetCookie(w, cookie)
- http.ParseCookie:解析HTTP请求头中的
Cookie
字段。
cookie, err := http.ParseCookie(r.Header.Get("Cookie"))
这些方法为处理HTTP请求和响应提供了基本的构建块,允许开发者构建功能丰富的HTTP服务和客户端。在使用net/http
包时,还应考虑错误处理、超时管理、保持连接活跃等高级特性。