Skip to content

Instantly share code, notes, and snippets.

@viggy28
Created June 5, 2021 15:37
Show Gist options
  • Select an option

  • Save viggy28/c08bf1a5a5f23a7dcfe2226c45925b0f to your computer and use it in GitHub Desktop.

Select an option

Save viggy28/c08bf1a5a5f23a7dcfe2226c45925b0f to your computer and use it in GitHub Desktop.

Revisions

  1. viggy28 created this gist Jun 5, 2021.
    21 changes: 21 additions & 0 deletions json-decoding.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    // 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)
    }