[golang/http] Compress the content returned by http

say up front

  • go version:go1.18.4 windows/amd64
  • Operating system: windows
  • Browser version: edge 104.0.1293.63 (official version) (64-bit)

Scenes

  • When using http for communication, when the amount of data is relatively large, it takes up a lot of bandwidth, and the data needs to be compressed to save bandwidth.

the code

func NewHttp() {
    
    
	http.HandleFunc("/my", myHandler)
	http.HandleFunc("/mycompress", myCompressHandler)

	err := http.ListenAndServe(":8183", nil)
	if err != nil {
    
    
		fmt.Println("err: ", err)
	}
}

func myCompressHandler(w http.ResponseWriter, r *http.Request) {
    
    
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Content-Encoding", "gzip")

	type St struct {
    
    
		Str string `json:"str"`
	}

	var str strings.Builder
	for i := 0; i < 100000; i++ {
    
    
		str.WriteByte(byte(rand.Int()))
	}

	// 使用gzip进行压缩 其他可选zlib等
	gw := gzip.NewWriter(w)
	defer gw.Close()

	err := json.NewEncoder(gw).Encode(&St{
    
    Str: str.String()})
	if err != nil {
    
    
		fmt.Println("encode err: ", err)
	}
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    
    
	w.Header().Set("Content-Type", "application/json")

	type St struct {
    
    
		Str string `json:"str"`
	}

	var str strings.Builder
	for i := 0; i < 100000; i++ {
    
    
		str.WriteByte(byte(rand.Int()))
	}

	err := json.NewEncoder(w).Encode(&St{
    
    Str: str.String()})
	if err != nil {
    
    
		fmt.Println("encode err: ", err)
	}
}

Compared

  • uncompressed
    insert image description here
  • After compression (because payloadit is a random string, the compression rate is relatively low)
    insert image description here

Client code

func ReqHttp() {
    
    
	req, err := http.NewRequest("Get", "http://127.0.0.1:8183/mycompress", nil)
	defer req.Body.Close()

	req.Header.Add("Accept-Encoding", "gzip")

	client := &http.Client{
    
    }
	resp, _ := client.Do(req)

	gr, err := gzip.NewReader(resp.Body)
	if err != nil {
    
    
		fmt.Println("decode err: ", err)
		return
	}
	defer gr.Close()

	type St struct {
    
    
		Str string `json:"str"`
	}

	tmp := &St{
    
    }
	err = json.NewDecoder(gr).Decode(tmp)
	if err != nil {
    
    
		fmt.Println("json decode err: ", err)
		return
	}

	fmt.Println(tmp.Str)
}

reference

Guess you like

Origin blog.csdn.net/qq_33446100/article/details/126624366