golang http gzip
阿新 • • 發佈:2018-11-15
當我們用http傳送訊息時,可以指定為gzip壓縮,對資料進行壓縮後再傳輸不僅可以節省頻寬還可以加快傳輸速度,對於雙方而言都是一件能夠取得更大收益的事情。
廢話不多說,直接上程式碼
http_server.go
1 package main 2 3 import ( 4 "compress/gzip" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "net/http" 9 ) 10 11 func handler(resp http.ResponseWriter, req *http.Request) { 12 13// var wr io.Writer 14 // wr = os.Stdout 15 // req.Header.Write(wr) 16 17 body, err := gzip.NewReader(req.Body) 18 if err != nil { 19 fmt.Println("unzip is failed, err:", err) 20 } 21 defer body.Close() 22 data, err := ioutil.ReadAll(body) 23 if err != nil && err != io.EOF {24 fmt.Println("-------------read all is failed.err:", err) 25 } 26 fmt.Println("===string(data)=", string(data)) 27 28 respJson := []byte(`{ 29 "rc": 70200, 30 "info_en": "success" 31 }`) 32 33 resp.Write(respJson) 34 } 35 36 func main() { 37 fmt.Println("http://localhost:9903/request") 38 http.HandleFunc("/request", handler) 39 http.ListenAndServe(":9903", nil) 40 }
http_client.go
1 package main 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "encoding/json" 7 "fmt" 8 "io/ioutil" 9 "net/http" 10 ) 11 12 func main() { 13 s := []byte(`{"adunitid":"08086D3CC2DC39741BBE1DC92945E022","api_ver":"1.4.8"}`) 14 data, err := json.Marshal(s) 15 if err != nil { 16 fmt.Println("marshal is faild,err: ", err) 17 } 18 19 var zBuf bytes.Buffer 20 zw := gzip.NewWriter(&zBuf) 21 if _, err = zw.Write(data); err != nil { 22 fmt.Println("-----gzip is faild,err:", err) 23 } 24 zw.Close() 25 httpRequest, err := http.NewRequest("POST", "http://localhost:9903/request", &zBuf) 26 if err != nil { 27 fmt.Println("http request is failed, err: ", err) 28 } 29 httpRequest.Header.Set("Accept-Encoding", "gzip") 30 client := http.Client{} 31 httpResponse, err := client.Do(httpRequest) 32 if err != nil { 33 fmt.Println("httpResponse is failed, err: ", err) 34 } 35 defer httpResponse.Body.Close() 36 37 body := httpResponse.Body 38 if httpResponse.Header.Get("Content-Encoding") == "gzip" { 39 body, err = gzip.NewReader(httpResponse.Body) 40 if err != nil { 41 fmt.Println("http resp unzip is failed,err: ", err) 42 } 43 defer body.Close() 44 } 45 data, err = ioutil.ReadAll(body) 46 if err != nil { 47 fmt.Println("read resp is failed, err: ", err) 48 } 49 50 fmt.Println("------data=", string(data)) 51 }