💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
官方文档:[https://golang.org/pkg/net/http/](https://golang.org/pkg/net/http/) # http客户端 http包提供客户端与服务端的能力 Get、Head、Post和PostForm发出HTTP(或HTTPS)请求: ~~~ resp, err := http.Get("http://example.com/") ... resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ... resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}}) ~~~ 完成响应正文后,客户端必须关闭它: ~~~ resp, err := http.Get("http://example.com/") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) // ... ~~~ 要控制HTTP客户端请求头、重定向策略和其他设置,请创建客户端: ~~~ client := &http.Client{ CheckRedirect: redirectPolicyFunc, } resp, err := client.Get("http://example.com") // ... req, err := http.NewRequest("GET", "http://example.com", nil) // ... req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req) // ... ~~~ 要控制代理、TLS配置、保持有效、压缩和其他设置,请创建传输: ~~~ tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("https://example.com") ~~~ 客户端和传输对于多个goroutine并发使用是安全的,为了提高效率,应该只创建一次并重新使用。 # http服务器 一个示例 ```golang import ( "log" "net/http" ) // GET /hello1 func hello(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("hello!")) } func main() { mux := &http.ServeMux{} mux.HandleFunc("/hello1", hello) // 路由 log.Fatal(http.ListenAndServe(":8080", mux)) // 启动服务 } ``` 敲入`go run app.go`运行 访问[http://localhost:8080/hello1](http://localhost:8080/hello1) 输出`hello!` ## server ListenAndServe使用给定的地址和处理程序启动HTTP服务器。通常情况下,emuhandler的意思是nilx。Handle和HandleFunc向DefaultServeMux添加处理程序: ~~~ http.Handle("/foo", fooHandler) http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) log.Fatal(http.ListenAndServe(":8080", nil)) ~~~ 通过创建自定义服务器,可以更好地控制服务器的行为: ~~~ s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) ~~~ 从Go1.6开始,当使用HTTPS时,http包对http/2协议有透明的支持。必须禁用HTTP/2的程序可以通过设置传输.TLSNextProto(针对客户)或服务器.TLSNextProto(对于服务器)到非零的空映射。或者,当前支持以下 GODEBUG环境变量: ~~~ GODEBUG=http2client=0 # disable HTTP/2 client support GODEBUG=http2server=0 # disable HTTP/2 server support GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs GODEBUG=http2debug=2 # ... even more verbose, with frame dumps ~~~ ## 静态文件服务器 ```golang http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) ``` 访问`http://localhost:8080/tmpfiles` 查看效果