一、HTTP 协议基础
HTTP(超文本传输协议)是用于传输诸如 HTML 等超媒体文档的应用层协议。
HTTP 请求由请求行、请求头部、空行和请求体组成。请求行包含请求方法(如 GET、POST 等)、请求的 URL 和 HTTP 协议版本。例如:
plaintext
GET /index.html HTTP/1.1
请求头部包含了如User - Agent(客户端标识)、Accept(可接受的内容类型)等信息,例如:
plaintext
User - Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q = 0.9,image/avif,image/webp,image/apng,*/*;q = 0.8,application/signed - exchange;v = b3;q = 0.9
HTTP 响应由响应行、响应头部、空行和响应体组成。响应行包含 HTTP 协议版本、响应状态码和状态描述。例如:
plaintext
HTTP/1.1 200 OK
响应头部包含如`Content - Type`(内容类型)、`Content - Length`(内容长度)等信息,例如:
plaintext
Content - Type: text/html; charset = UTF - 8 Content - Length: 1234
**二、在 Go 中处理 HTTP 请求**
在 Go 语言中,可以使用`net/http`包来构建 Web 服务器和处理 HTTP 请求。
构建一个简单的 Hello World Web 服务器:
go
package main
import ( "fmt" "net/http" )
func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }
func main() { http.HandleFunc("/", helloHandler) http.ListenAndServe(":8080", nil) }
当有客户端访问`http://localhost:8080`时,就会返回`Hello, World!`。
如果要处理不同的请求方法,例如 POST 请求,可以这样做:
收起
go
func postHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { r.ParseForm() // 获取POST表单中的数据 username := r.FormValue("username") password := r.FormValue("password") fmt.Fprintf(w, "Received username: %s and password: %s", username, password) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } }
将`http.HandleFunc("/post", postHandler)`添加到`main`函数中,就可以处理`/post`路径下的 POST 请求。