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
After compression (because payloadit is a random string, the compression rate is relatively low)