go http client & server gzip数据压缩格式

server端:

package main

import (
	"compress/gzip"
	"fmt"
	"io/ioutil"
	"net/http"
)

func handler(w http.ResponseWriter,  req *http.Request)  {
	reader, e := gzip.NewReader(req.Body)
	if e!= nil{
		_, _ = fmt.Fprint(w, e.Error())
		return
	}

	all, e := ioutil.ReadAll(reader)
	if e!= nil{
		_, _ = fmt.Fprint(w, e.Error())
		return
	}else {
		fmt.Println(string(all))
		_, _ = fmt.Fprint(w, string(all))
	}

}

func main() {
	http.HandleFunc("/", handler)
	_ = http.ListenAndServe(":9090", nil)
}

client端:

package main

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io/ioutil"
	"net/http"
)

var url = "http://127.0.0.1:9090"

func main() {


	var zBuf bytes.Buffer
	zw := gzip.NewWriter(&zBuf)
	if _, err := zw.Write([]byte("hello world")); err != nil {
		panic(err)
	}
	zw.Close()
	
	httpRequest, err := http.NewRequest("POST", url, &zBuf)
	if err != nil{
		panic(err)
	}
	httpRequest.Header.Set("Content-Encoding", "gzip")
	
	client := http.Client{}
	response, err := client.Do(httpRequest)
	if err!= nil{
		panic(err)
	}
	if all, err := ioutil.ReadAll(response.Body);err != nil{
		panic(err.Error())
	}else {
		fmt.Println(string(all))
	}

}

 

你可能感兴趣的:(golang,golang,gzip)