golang http gzip

当我们用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  {
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         }
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 }

 

转载于:https://www.cnblogs.com/chaselogs/p/9964487.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值