Converting Structure into byte data and vice versa in golang

huangapple go评论77阅读模式
英文:

Converting Structure into byte data and vice versa in golang

问题

我正在写一个Go程序,只是从服务器获取响应。我使用以下代码:

tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
link := "服务器地址"
resp, err := client.Get(link)

现在我需要将resp转换为字节,以便我可以将其传递给某个函数,然后另一端可以将其解码为相同的结构体。resp是http包中定义的http.Response类型的结构体,我无法更改它。

我想直接将其转换为字节。

在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.

答案1

得分: 6

你想要使用Go语言库中的encode包。通常我喜欢使用JSON编码,因为它非常易读,但该包支持编码和解码到多种格式,包括二进制和gob,后者是专门为你尝试做的事情设计的格式。

以下是从Go 文档中提取的编码为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)
}

以下是从Go 文档中提取的从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)
}
英文:

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

答案2

得分: 0

这是翻译好的内容:

这个怎么样?

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

你可以将其作为字节使用,或者像这样简单地将其转换为字符串

bodyString := string(bodyBytes)

英文:

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)

答案3

得分: 0

http.Response太复杂了,无法转换为字节然后恢复。
但是对于简单的结构体,你可以考虑使用gob,它专门用于:

> 在网络上传输数据结构或将其存储在文件中,必须对其进行编码,然后再进行解码。

英文:

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.

答案4

得分: 0

net/http/httputil包中的DumpResponse函数可能会有用。

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

文档提供了一个示例。

英文:

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

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

The documentation provides an example.

答案5

得分: -1

我不确定是否误解了你的问题。但是这里有一个将结构体转换为[]byte,以及将[]byte转换为结构体的示例。

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
}

请注意,这是一个Go语言的示例代码,用于演示如何进行结构体和[]byte之间的转换。

英文:

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
}

huangapple
  • 本文由 发表于 2014年10月16日 03:25:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/26390503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定