I have a very simple Go webserver. It's job is to receive an inbound json payload. It then publishes the payload to one or more services that expect a byte array. The payload doesn't need to be checked. Just sent over.

In this case, it receives an inbound job and sends it to Google PubSub. It might be another service - it doesn't really matter. I'm trying to find the most efficient way to convert the object to a byte array without first decoding it.

Why? Seems a bit wasteful to decode and convert to JSON on one server, only to unmarshal it later. Plus, I don't want to maintain two identical structs in two packages.

How is it possible to convert the io.ReadCloser to a byte array so I only need to unmarshal once. I tried something like this answer but don't think that's the most efficient way either:

From io.Reader to string in Go

My http server code looks like this:

func Collect(d DbManager) http.HandlerFunc {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=utf-8")

    code := 422
    obj := Report{}
    response := Response{}
    response.Message = "Invalid request"

    decoder := json.NewDecoder(r.Body)
    decoder.Decode(&obj)

    if obj.Device.MachineType != "" {
        msg,_ := json.Marshal(obj)
        if d.Publish(msg, *Topic) {
          code = 200
        }
        response.Message = "Ok"
    }

    a, _ := json.Marshal(response)
    w.WriteHeader(code)
    w.Write(a)
    return
})
}

推荐答案

You convert a Reader to bytes, by reading it. There's not really a more efficient way to do it.

body, err := ioutil.ReadAll(r.Body)

If you are unconditionally transferring bytes from an io.Reader to an io.Writer, you can just use io.Copy

Json相关问答推荐

当有2个嵌套数组时展平复杂的JSON

Pandas 对REST API的自定义响应

错误:在 NX 工作区中找不到模块../swagger.json

使用 jq 从带有转义反斜杠字符的嵌套 JSON 中提取数据

Ansible - 将文件内容添加到字典中

Jolt 变换以展平 json 字符串数组

在 PowerShell 中通过 aws cli 创建 cloudwatch alert 时出现字符串解析错误

根据值过滤输入的JSON并使用它准备预期的输出

从字节解码 JSON 数据,将 float 值更改为 int

从 JSON 响应中获取最新版本发布字段

通过一个序列化器更新多个模型数据

在 Flutter 中将对象转换为可编码对象失败

Jolt - 在同一级别添加时组合值的问题

N1QL 聚合查询 Couchbase

Golang / Go - 如果 struct 没有字段,如何将其编组为空?

如何使用 LINQ 在 C# 中重构对象?

python,将Json写入文件

编写 JSON 日志(log)文件的格式?

如何通过 NSJSONSerialization 在 JSON 中包含空值?

Gson 将一组数据对象转换为 json - Android