Skip to content

Instantly share code, notes, and snippets.

@zckkte
Last active November 5, 2024 09:14
Show Gist options
  • Select an option

  • Save zckkte/46028ab75837d7cf68fe2c72fde131bd to your computer and use it in GitHub Desktop.

Select an option

Save zckkte/46028ab75837d7cf68fe2c72fde131bd to your computer and use it in GitHub Desktop.
func readJson[T any](w http.ResponseWriter, r *http.Request) (T, error) {
maxBytes := 1_048_576
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var dst T
if err := dec.Decode(&dst); err != nil {
return dst, err
}
err := dec.Decode(&struct{}{})
if err != io.EOF {
return dst, errors.New("body must only contain a single JSON object")
}
return dst, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment