101 lines
1.9 KiB
Go
101 lines
1.9 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"mime"
|
|
"net/http"
|
|
"slices"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const maxJSONBody = 1 << 20 // 1 MiB
|
|
|
|
func readJSON(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
dst any,
|
|
requiredFields ...string,
|
|
) bool {
|
|
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
if err != nil || mediaType != "application/json" {
|
|
writeError(
|
|
w,
|
|
http.StatusUnsupportedMediaType,
|
|
"unsupported_media_type",
|
|
"Content-Type must be application/json",
|
|
)
|
|
return false
|
|
}
|
|
|
|
defer r.Body.Close()
|
|
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONBody+1))
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "Cannot read body")
|
|
return false
|
|
}
|
|
|
|
if len(body) > maxJSONBody {
|
|
writeError(
|
|
w,
|
|
http.StatusRequestEntityTooLarge,
|
|
"payload_too_large",
|
|
"JSON body is too large",
|
|
)
|
|
return false
|
|
}
|
|
|
|
invalid := func() bool {
|
|
writeError(
|
|
w,
|
|
http.StatusBadRequest,
|
|
"invalid_request",
|
|
"Invalid JSON body",
|
|
)
|
|
return false
|
|
}
|
|
|
|
if !utf8.Valid(body) {
|
|
return invalid()
|
|
}
|
|
|
|
var fields map[string]json.RawMessage
|
|
if err := json.Unmarshal(body, &fields); err != nil || fields == nil {
|
|
return invalid()
|
|
}
|
|
|
|
for name := range fields {
|
|
if !slices.Contains(requiredFields, name) {
|
|
return invalid()
|
|
}
|
|
}
|
|
|
|
for _, name := range requiredFields {
|
|
value, exists := fields[name]
|
|
if !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
|
|
return invalid()
|
|
}
|
|
}
|
|
|
|
decoder := json.NewDecoder(bytes.NewReader(body))
|
|
decoder.DisallowUnknownFields()
|
|
|
|
if err := decoder.Decode(dst); err != nil {
|
|
return invalid()
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, body any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
|
|
if err := json.NewEncoder(w).Encode(body); err != nil {
|
|
log.Printf("cannot write JSON response: %v", err)
|
|
}
|
|
}
|