1. 客户端
Http Client:
- http.GET(url) 直接发起请求
- http.Client{} 控制请求头部等
- httputil 简化工作
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| func main() {
req, err := http.NewRequest( http.MethodGet, "http://www.baidu.com", nil) req.Header.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
client := http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { fmt.Println("Redirect:", req) return nil }, } resp, err := client.Do(req)
if err != nil { panic(err) } defer resp.Body.Close()
content, err := httputil.DumpResponse(resp, true) if err != nil { panic(err) }
fmt.Printf("%s", content) }
|
2. 服务端
2.1 handler函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| func SignupHandler(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { data, err := ioutil.ReadFile("./static/view/signup.html") if err != nil { w.WriteHeader(http.StatusInternalServerError) return }
w.Write(data) } else { r.ParseForm() username := r.Form.Get("username") password := r.Form.Get("password")
if len(username) < 3 || len(password) < 5 { w.Write([]byte("Invalid parameter")) return }
enc_pwd := util.Sha1([]byte(password + pwd_salt)) ret := db.UserSignup(username, enc_pwd) if ret { w.Write([]byte("SUCCESS")) } else { w.Write([]byte("FAILED")) } } }
|
2.2 中间件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| func HTTPInterceptor(h http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { r.ParseForm() username := r.Form.Get("username") token := r.Form.Get("token")
if len(username) < 3 || !IsTokenValid(token) { w.WriteHeader(http.StatusForbidden) return }
h(w, r) }) }
|
2.3 启动服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| func main() { path, _ := os.Getwd() path = filepath.Join(path, "static") http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(path))))
http.HandleFunc("/user/signup", handler.SignupHandler) http.HandleFunc("/user/info", handler.HTTPInterceptor(handler.UserInfoHandler))
err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatalf("Failed to start server: %v", err) } }
|
3. http服务器性能分析
import _ "net/http/pprof
- 访问
/debug/pprof/
- 使用
go tool pprof
分析性能
1 2 3 4 5 6 7
| import ( "log" "net/http" _ "net/http/pprof" "os" ... )
|
查看性能:
http://localhost:8080/debug/pprof/
go tool pprof http://localhost:8080/debug/pprof/profile