在进行网络通信时,如果需要将数据或自定义的数据结构进行传输就需要先将数据先编码后再解码。Gob(go binary)golang标准库中用于将数据以二进制形式序列化和反序列化的工具,其可以实现高效的序列化,且和JSON一样在发送端对数据结构进行编码,接收端再将数据解码转化为本地变量。


以传输Map数据为例子
贴上服务端代码:

type MyMux struct {
}

var mp =map[string]int{"a":1,"b":2}

func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/getmap" {
    w.Write(encode(&mp))
    return
    }else if r.URL.Path == "/error" {
    w.WriteHeader(401)
    fmt.Fprintln(w,"Sorry!")
    return
     }
     http.NotFound(w, r)
     return
}

//encode map[string]int to []byte
func encode(data interface{}) []byte{
      m := new(bytes.Buffer)
      enc := gob.NewEncoder(m)//Create a encoder
      err := enc.Encode(data) //encode
      if err!=nil{
    panic(err)
      }
      return m.Bytes()
}

func main() {
       mux := &MyMux{}
       http.ListenAndServe(":9090", mux)
}

客户端代码

func load(e interface{}, buf io.ReadCloser) {
    dec := gob.NewDecoder(buf)

    err := dec.Decode(e)
    if err != nil {
        panic(err)
    }
}

func main(){
    client:=&http.Client{}
    req,err:=http.NewRequest("GET","http://localhost:9090/getmap",nil)
    if err!=nil{
        fmt.Println(err)
        return
    }
    resp,err:=client.Do(req)
    getmp:=make(map[string]int,2)
    dec:=gob.NewDecoder(resp.Body)
    err=dec.Decode(&getmp)
    if err!=nil{
        panic(err)
    }
    for k,v:=range getmp{
        fmt.Println(k,v)
    }
}

客户端输出:

Last modification:September 4th, 2023 at 10:12 pm
If you think my article is useful to you, please feel free to appreciate