Go 在標準庫中內置了功能強大的?
net/http
?包,可快速構建高并發、高性能的 HTTP 服務,廣泛應用于微服務、Web后端、API中間層等場景。
一、快速創建一個HTTP服務
示例:最簡Hello服務
package?mainimport?("fmt""net/http"
)func?helloHandler(w?http.ResponseWriter,?r?*http.Request)?{fmt.Fprintf(w,?"Hello,?Go?Web!")
}func?main()?{http.HandleFunc("/",?helloHandler)fmt.Println("Listening?on?http://localhost:8080/")http.ListenAndServe(":8080",?nil)
}
二、請求與響應對象詳解
- ??
http.Request
:封裝了客戶端請求的所有信息(URL、Header、Body等) - ??
http.ResponseWriter
:用于構造服務器的響應
示例:獲取請求信息
func?infoHandler(w?http.ResponseWriter,?r?*http.Request)?{fmt.Fprintf(w,?"Method:?%s\n",?r.Method)fmt.Fprintf(w,?"URL:?%s\n",?r.URL.Path)fmt.Fprintf(w,?"Header:?%v\n",?r.Header)
}
三、處理URL參數與POST數據
1. 獲取查詢參數
func?queryHandler(w?http.ResponseWriter,?r?*http.Request)?{name?:=?r.URL.Query().Get("name")fmt.Fprintf(w,?"Hello,?%s!",?name)
}
訪問:http://localhost:8080/query?name=Go
2. 處理表單數據(POST)
func?formHandler(w?http.ResponseWriter,?r?*http.Request)?{r.ParseForm()username?:=?r.FormValue("username")fmt.Fprintf(w,?"Welcome,?%s!",?username)
}
四、自定義HTTP路由與Handler
使用?http.ServeMux
func?main()?{mux?:=?http.NewServeMux()mux.HandleFunc("/hello",?helloHandler)mux.HandleFunc("/info",?infoHandler)http.ListenAndServe(":8080",?mux)
}
使用第三方路由器(如?gorilla/mux
、chi
?等)
//?示例略,可根據需要引入第三方庫
五、構建HTTP客戶端請求
Go 提供了強大的?http.Client
?支持 GET/POST 等請求。
示例:GET請求
resp,?err?:=?http.Get("https://httpbin.org/get")
defer?resp.Body.Close()
body,?_?:=?io.ReadAll(resp.Body)
fmt.Println(string(body))
示例:POST請求
data?:=?url.Values{"name":?{"Go"}}
resp,?err?:=?http.PostForm("https://httpbin.org/post",?data)
defer?resp.Body.Close()
六、JSON接口的處理
JSON響應
func?jsonHandler(w?http.ResponseWriter,?r?*http.Request)?{type?Resp?struct?{Status?string?`json:"status"`}w.Header().Set("Content-Type",?"application/json")json.NewEncoder(w).Encode(Resp{"ok"})
}
JSON請求解析
func?receiveJSON(w?http.ResponseWriter,?r?*http.Request)?{type?Req?struct?{Name?string?`json:"name"`}var?data?Reqjson.NewDecoder(r.Body).Decode(&data)fmt.Fprintf(w,?"Hello,?%s",?data.Name)
}
七、靜態文件服務
http.Handle("/static/",?http.StripPrefix("/static/",?http.FileServer(http.Dir("public"))))
訪問?/static/index.html
?實際讀取?public/index.html
?文件。
八、HTTP中間件的編寫
中間件常用于實現日志、認證、限流等功能。
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)})
}
九、啟動HTTPS服務(SSL)
http.ListenAndServeTLS(":443",?"cert.pem",?"key.pem",?nil)
用于生產環境時,請使用自動證書工具如 Let’s Encrypt + Caddy/Nginx 做代理。
十、總結
能力 | 工具與API |
啟動Web服務 | http.ListenAndServe |
構造REST接口 | HandlerFunc ?+ JSON 編解碼 |
發起HTTP請求 | http.Get ,?http.Post ,?http.Client |
路由與中間件 | ServeMux ?或第三方路由器 |
文件服務與HTTPS | http.FileServer ?/?ListenAndServeTLS |