在Golang中将结构转换为字节数据,反之亦然

I am writing a Go program in which I am just geting response from server using -

tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
client := &http.Client{Transport: tr}
link := "address of server"
resp, err := client.Get(link)

Now I need to convert resp into bytes so that I can pass it to some function and other side can decode it into the same structure. resp is a structure of http.Response type defined in http package that I can not change.

I want to convert it directly into bytes.

Is there any such function in golang which I can directly use or is there any way exist to do the same.

You want to use the encode package from go's library. Usually I like the JSON encoding because it's very human readable, but the package supports encoding to/from many formats including binary and gob which is a format designed just for what you are trying to do.

Example from the go documentation to encode to json:

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    type ColorGroup struct {
        ID     int
        Name   string
        Colors []string
    }
    group := ColorGroup{
        ID:     1,
        Name:   "Reds",
        Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    }
    b, err := json.Marshal(group)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
}

Example from the go documentation to decode from json:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var jsonBlob = []byte(`[
        {"Name": "Platypus", "Order": "Monotremata"},
        {"Name": "Quoll",    "Order": "Dasyuromorphia"}
    ]`)
    type Animal struct {
        Name  string
        Order string
    }
    var animals []Animal
    err := json.Unmarshal(jsonBlob, &animals)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Printf("%+v", animals)
}

What about this?

bodyBytes, err := ioutil.ReadAll(response.Body)

You can use this as bytes or simply convert ir to string like this

bodyString := string(bodyBytes)

http.Response is too involved to be converted to bytes and then be restored. But for simple struct, you may consider using gob which is designed for:

To transmit a data structure across a network or to store it in a file, it must be encoded and then decoded again.