forked from mtusi2026/mtusi2026lab2
61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
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 decodeJSONStrict(r *http.Request, dst any) error {
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(dst); err != nil {
|
|
if err == io.EOF {
|
|
return fmt.Errorf("empty body")
|
|
}
|
|
return err
|
|
}
|
|
if dec.More() {
|
|
return fmt.Errorf("trailing data after JSON body")
|
|
}
|
|
return nil
|
|
}
|