Files
mtusi2026lab3/internal/httpapi/httpx.go
2026-10-23 00:00:08 +03:00

92 lines
2.0 KiB
Go

package httpapi
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"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"
)
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 {
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
}