henryspace

记录精彩的程序人生 开始使用

Part 26 - Go 语言学习 - HTTP 标准库

HTTP标准库

  1. 使用http客户端发送请求
package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
)

func main() {
	resp, err := http.Get("https://www.imooc.com")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	s, err := httputil.DumpResponse(resp, true)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", s)
}

  1. 使用http.Client控制请求头部等
  2. 使用httputil简化工作
package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
)

func main() {
	request, err := http.NewRequest(http.MethodGet,
		"https://www.imooc.com",
		nil)
	if err != nil {
		panic(err)
	}
	request.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(request)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	s, err := httputil.DumpResponse(resp, true)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", len(s))
}

http服务器的性能分析

  1. import _ "net/http/prof"
  2. 访问/debug/pprof/
  3. 使用go tool pprof分析性能
package main

import (
	"io"
	"net/http"
	_ "net/http/pprof" // 引入pprof进行性能分析
)

func HelloServer(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "hello, world!\n")
}

func main() {
	http.HandleFunc("/", HelloServer)

	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		panic(err)
	}
}

1. 本地查看性能分析数据 http://localhost:8888/debug/pprof
2. 得到cpu性能数据go tool -pprof http://localhost:8888/debug/pprof/profile

评论
留下你的脚步
推荐阅读