Skip to content

Instantly share code, notes, and snippets.

@viggy28
Created June 5, 2021 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viggy28/c08bf1a5a5f23a7dcfe2226c45925b0f to your computer and use it in GitHub Desktop.
Save viggy28/c08bf1a5a5f23a7dcfe2226c45925b0f to your computer and use it in GitHub Desktop.
// There are two ways I can convert json body to struct. Don't know what's the difference.
// https://www.reddit.com/r/golang/comments/5yhfo1/jsondecoder_vs_jsonunmarshal/
// Other than reddit reference I don't see any other links.
//Method1:
var c Service
byteArray, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Fatalf("fatal: reading from readall body %v", req.Body)
}
err = json.Unmarshal(byteArray, &c)
if err != nil {
log.Fatalf("fatal: reading from readall body %v", req.Body)
}
//Method2:
var c Service
err = json.NewDecoder(req.Body).Decode(&c)
if err != nil {
log.Fatalf("fatal: reading request body %v", req.Body)
}
@viggy28
Copy link
Author

viggy28 commented Jun 5, 2021

@theckman in Golang slack community responded with:

if it's an HTTP request (a single JSON document), use Unmarshal
If it was a TCP connection, where the remote end would continually send JSON objects to you, then you would use the decoder. Since that's designed for a stream of JSON documents and not just one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment