Last active
November 5, 2024 09:14
-
-
Save zckkte/46028ab75837d7cf68fe2c72fde131bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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