Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Structure into byte data and vice versa in golang

Tags:

go

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.

like image 935
susheel chaudhary Avatar asked Oct 15 '25 18:10

susheel chaudhary


1 Answers

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)
}
like image 138
Topo Avatar answered Oct 17 '25 10:10

Topo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!