13.1 http标准库

一、HTTP

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

  2. 使用http.Client控制请求头部等

  3. 使用httputil简化工作

  4. 简单get请求案例

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httputil"
    )
    
    func main() {
    	// 控制请求头再请求
    	request, err := http.NewRequest(http.MethodGet, "http://www.imooc.com", nil)
    	// 设置请求头
    	request.Header.Add("token", "asdfghjkl")
    
    	// 自定义client
    	client := http.Client{
    		CheckRedirect: func(req *http.Request, via []*http.Request) error {
    			fmt.Println("请求地址:", req)
    			return nil
    		},
    	}
    	
    	// 自定义client请求
    	resp, err := client.Do(request)
    	
    	// // 控制请求头请求
    	// resp, err := http.DefaultClient.Do(request)
    	
    	// 直接请求
    	// resp, err := http.Get("http://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)
    }

二、HTTP服务器的性能分析

  1. import _"net/http/pprof" // 导包,加下划线表示即便没有用到,也不会报错、清除

  2. 访问/debug/pprof/(在页面查看即可)

  3. 使用go tool pprof 地址/debug/profile命令行命令分析性能

Last updated

Was this helpful?