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
})
}