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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?