forked from mtusi2026/mtusi2026lab5
lab5 na4
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type errorCode string
|
||||
|
||||
const (
|
||||
codeInvalidRequest errorCode = "invalid_request"
|
||||
codeUnauthorized errorCode = "unauthorized"
|
||||
codeNotFound errorCode = "not_found"
|
||||
codeConflict errorCode = "conflict"
|
||||
codeUnavailable errorCode = "unavailable"
|
||||
codeInternal errorCode = "internal_error"
|
||||
codeTooLarge errorCode = "payload_too_large"
|
||||
codeUnsupportedMedia errorCode = "unsupported_media_type"
|
||||
)
|
||||
|
||||
func newRequestID() string {
|
||||
b := make([]byte, 12)
|
||||
_, _ = rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, requestID string, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(status)
|
||||
if payload != nil {
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, requestID string, code errorCode, message string) {
|
||||
writeJSON(w, status, requestID, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func jsonFieldNames(dst any) map[string]bool {
|
||||
names := map[string]bool{}
|
||||
t := reflect.TypeOf(dst)
|
||||
for t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
tag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0]
|
||||
if tag != "" && tag != "-" {
|
||||
names[tag] = true
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
func decodeJSONStrict(r *http.Request, dst any) error {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return fmt.Errorf("unsupported Content-Type")
|
||||
}
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return fmt.Errorf("empty body")
|
||||
}
|
||||
var probe map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &probe); err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := jsonFieldNames(dst)
|
||||
for k := range probe {
|
||||
if !allowed[k] {
|
||||
return fmt.Errorf("unknown field %q", k)
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
if dec.More() {
|
||||
return fmt.Errorf("trailing data after JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user