susheel chaudhary
susheel chaudhary

Reputation: 271

Converting Structure into byte data and vice versa in 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.

Upvotes: 4

Views: 28499

Answers (5)

abvarun226
abvarun226

Reputation: 621

DumpResponse function from net/http/httputil package might be useful.

https://pkg.go.dev/net/http/httputil#example-DumpResponse

The documentation provides an example.

Upvotes: 0

user12817546
user12817546

Reputation:

I'm not sure if I misunderstood your question. But here is an example of how to convert a struct to a []byte and vice versa.

package main

import "fmt"

func main() {
    type S struct{ s string }
    st := S{"address of server"}
    fmt.Printf("%T %v\n", st, st.s) //main.S test
    //convert struct to []byte
    sl := []byte(st.s)
    fmt.Printf("%T %v\n", sl, sl) //[]uint8 [97 100 ... 114]
    //convert []byte to struct
    s := fmt.Sprintf("%s", sl)
    st2 := S{s}
    fmt.Printf("%T %v\n", st2, st2.s) //main.S test
}

Upvotes: -1

heading
heading

Reputation: 721

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.

Upvotes: 0

SokIsKedu
SokIsKedu

Reputation: 316

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)

Upvotes: 0

Topo
Topo

Reputation: 5002

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)
}

Upvotes: 6

Related Questions