go的net/http库通过handler和handlefunc等核心概念,可快速构建http服务器和客户端。1. 创建http服务器需使用http.handlefunc注册处理函数,并调用http.listenandserve启动服务;2. 发送get请求可通过http.get实现;3. 处理post请求需解析r.form并读取表单数据;4. 自定义客户端超时时间可通过设置http.client的timeout字段;5. 操作header信息通过r.header.get读取并用w.header().set设置;6. 实现中间件可通过包装handler的方式;7. 管理Cookie则借助http.cookie结构体进行读写操作。这些功能使开发者能够高效完成常见web任务。
Go的
net/http
库,用起来就像搭积木一样,能快速构建HTTP服务器和客户端。核心就是理解Handler和HandleFunc,以及Request和Response结构体。
Go的
net/http
库为开发者提供了便捷的工具,可以轻松实现HTTP服务器和客户端。理解并掌握其核心概念和用法,能够显著提高Web开发的效率和质量。
如何创建一个简单的HTTP服务器?
创建一个HTTP服务器,最简单的方法是使用
http.HandleFunc
注册一个处理函数,然后调用
http.ListenAndServe
启动服务器。例如:
立即学习“go语言免费学习笔记(深入)”;
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
这段代码注册了一个处理根路径的handler函数,当有请求到达根路径时,会返回”Hello, World!”。
http.ListenAndServe
监听8080端口,并开始处理HTTP请求。nil表示使用默认的ServeMux。
如何发送一个HTTP GET请求?
使用
http.Get
函数可以发送一个简单的GET请求。例如:
package main import ( "fmt" "net/http" "io/ioutil" ) func main() { resp, err := http.Get("https://www.example.com") if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error:", err) return } fmt.Println(String(body)) }
这段代码发送一个GET请求到
https://www.example.com
,然后读取响应的内容并打印出来。注意要关闭
resp.Body
,防止资源泄露。
如何处理HTTP POST请求?
处理POST请求需要从
Request
对象中读取数据。例如,从form表单中读取数据:
package main import ( "fmt" "net/http" ) func formHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { err := r.ParseForm() if err != nil { fmt.Fprintf(w, "ParseForm() err: %v", err) return } fmt.Fprintf(w, "POST request successfuln") name := r.FormValue("name") address := r.FormValue("address") fmt.Fprintf(w, "Name = %sn", name) fmt.Fprintf(w, "Address = %sn", address) } else { fmt.Fprintf(w, "Only POST method is supported.") } } func main() { http.HandleFunc("/form", formHandler) http.ListenAndServe(":8080", nil) }
这个例子中,
r.ParseForm()
用于解析form表单数据,然后可以使用
r.FormValue
读取特定字段的值。
如何自定义HTTP客户端的超时时间?
默认情况下,
http.Client
使用默认的超时时间。可以创建一个自定义的
http.Client
,并设置
Timeout
字段来修改超时时间。
package main import ( "fmt" "net/http" "time" ) func main() { client := &http.Client{ Timeout: time.Second * 10, } resp, err := client.Get("https://www.example.com") if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() // ... 处理响应 }
这段代码创建了一个超时时间为10秒的HTTP客户端。
如何处理HTTP请求中的header信息?
可以通过
Request
对象的
Header
字段访问HTTP请求的header信息。
Header
是一个
map[string][]string
类型,可以方便地读取和设置header。
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { userAgent := r.Header.Get("User-Agent") fmt.Fprintf(w, "User-Agent: %sn", userAgent) w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
这个例子中,读取了请求的
User-Agent
header,并设置了响应的
Content-Type
header。
如何实现HTTP中间件?
HTTP中间件是一种在处理请求之前或之后执行某些操作的模式。可以通过创建一个函数来包装现有的handler来实现中间件。
package main import ( "fmt" "net/http" "log" ) func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("Request: %s %s", r.Method, r.URL.Path) next.ServeHTTP(w, r) }) } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.Handle("/", loggingMiddleware(http.HandlerFunc(handler))) http.ListenAndServe(":8080", nil) }
这个例子中,
loggingMiddleware
是一个中间件,它会在处理请求之前记录请求的method和URL。
如何处理HTTP cookies?
可以使用
http.Cookie
结构体来处理HTTP cookies。
http.ReadRequest
用于读取请求中的cookies,
http.SetCookie
用于设置响应的cookies。
package main import ( "fmt" "net/http" ) func cookieHandler(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("mycookie") if err != nil { fmt.Println("Cookie not found") cookie = &http.Cookie{ Name: "mycookie", Value: "initial value", Path: "/", } } fmt.Fprintf(w, "Cookie value: %sn", cookie.Value) cookie.Value = "updated value" http.SetCookie(w, cookie) } func main() { http.HandleFunc("/cookie", cookieHandler) http.ListenAndServe(":8080", nil) }
这个例子中,读取名为”mycookie”的cookie,如果不存在则创建一个,然后更新cookie的值并设置到响应中。
这些示例涵盖了
net/http
库的一些基本用法,足以开始构建简单的HTTP服务器和客户端。更深入的用法,比如HTTPS、websocket等,可以参考官方文档。