The most efficient way to convert io.ReadCloser to a byte array

I have a very simple Go web server. The challenge is to get the incoming json payload. It then publishes a payload for one or more services waiting for an array of bytes. The payload does not need to be checked. Just sent.

In this case, he receives the incoming job and sends it to Google PubSub. It may be another service - it does not really matter. I am trying to find the most efficient way to convert an object to an array of bytes without first decoding it.

Why? It seems a little wasteful for decoding and converting to JSON on a single server, only for its further decoupling. In addition, I do not want to support two identical structures in two packages.

How can I convert io.ReadCloser to an array of bytes, so I only need to unmount it once. I tried something like this answer, but I don't think the most efficient way is:

From io.Reader to a line in Go

My http server code is as follows:

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 }) } 
+5
source share
1 answer

You convert Reader to bytes by reading it. There is really no more efficient way to do this.

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

If you unconditionally transfer bytes from io.Reader to io.Writer , you can simply use io.Copy

+11
source

Source: https://habr.com/ru/post/1257935/


All Articles