Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Double curly brackets in struct when using in Decode(&struct{}{})

I have this function in some code , i dont understand what are the double curly brackets in struct that help do decide that its not 2 jsons ?
How does it work ?

func readJSON(w http.ResponseWriter,r *http.Request,data interface{}) error {
    maxBytes := 1024 * 1024 
    r.Body = http.MaxBytesReader(w,r.Body,int64(maxBytes))
    dec := json.NewDecoder(r.Body)
    dec.DisallowUnknownFields()
    err := dec.Decode(data)

    if err != nil {
        return err
    }

    err = dec.Decode(&struct{}{})
    if err != io.EOF {
        return errors.New("Body must Only contain 1 json ")
    }
    
    return nil
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Let’s break it down:

  • struct{} is a type: a struct with no fields.
  • struct{}{} is a literal value: a new instance of the above type.
  • &struct{}{} is a pointer to the above literal value.

By attempting to decode JSON a second time, it confirms that the body does not have a second JSON document after the first, for example:

{
  "foo": "bar"
}
{
  "foo": "qux"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading