Go HTTP包
介绍
Go 语言的标准库中提供了一个强大的 net/http
包,用于构建 Web 服务器和处理 HTTP 请求与响应。无论是构建简单的 API 还是复杂的 Web 应用,net/http
包都能满足你的需求。本文将带你从零开始学习如何使用 Go 的 HTTP 包,并通过实际案例展示其应用。
基本概念
HTTP 服务器
在 Go 中,创建一个 HTTP 服务器非常简单。你只需要使用 http.ListenAndServe
函数,并指定监听的地址和处理请求的处理器(Handler)。
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 服务器,监听在 8080
端口。当用户访问根路径 /
时,服务器会返回 "Hello, World!"。
处理 HTTP 请求
HTTP 请求的处理是通过 http.HandlerFunc
或 http.Handler
接口来实现的。http.HandlerFunc
是一个函数类型,它接受两个参数:http.ResponseWriter
和 *http.Request
。
http.ResponseWriter
:用于向客户端发送响应。*http.Request
:包含客户端发送的请求信息。