dtp87205 2016-10-09 16:40
浏览 274
已采纳

将io.ReadCloser转换为字节数组的最有效方法

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
})
}
  • 写回答

1条回答 默认 最新

  • douchen4534 2016-10-09 17:35
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100