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.

在本例中,它接收入站作业(job)并将其发送到Google PubSub.这可能是另一项服务-这真的无关紧要.I'm trying to find the most efficient way to convert the object to a byte array without first decoding it.

为什么?在一台服务器上解码并转换为JSON似乎有点浪费,只是在以后将其解组.另外,我不想在两个包中维护两个相同的 struct .

如何转换io.ReadCloser接近字节数组,所以我只需要解组一次.我try 过这样的答案,但也不认为这是最有效的方法:

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相关问答推荐

合并二维数组的Jolt表达式

如何使用Aeson解码带有Unicode字符的JSON文件?

在AWS步骤函数中将字符串解析为JSON&S映射状态

在Zig中解析JSON失败

报告重复的对象键

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

APIM 生成 JsonArray 到 EventHub

我如何将 JSON 格式与 flutter 一起使用?帮助使用 Gamebanana api

如何在linux中用jq过滤json数组?

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

使用 jq Select 键:值并输出为数组

在 json 嵌入的 YAML 文件中 - 使用 Python 仅替换 json 值

如何使用 Serde 使用顶级数组反序列化 JSON?

如何将任意 json 对象发布到 webapi

如何从 mysql 数据库构建 JSON 数组

PostgreSQL 中的 JSON 模式验证?

与classic 规范化表相比,postgres JSON 索引是否足够高效?

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

JSON.stringify 向我的 Json 对象添加额外的 \ 和 "" 的问题