package httpapi import ( "encoding/json" "errors" "fmt" "io" "net/http" "strings" ) // Envelope is the single response shape of the panel API. type Envelope struct { Code int `json:"code"` Msg string `json:"msg"` Data any `json:"data,omitempty"` } // APIError carries an HTTP status and a user facing message. type APIError struct { Status int Msg string } func (e *APIError) Error() string { return e.Msg } // Errorf builds an APIError. func Errorf(status int, format string, args ...any) *APIError { return &APIError{Status: status, Msg: fmt.Sprintf(format, args...)} } func badRequest(format string, args ...any) *APIError { return Errorf(http.StatusBadRequest, format, args...) } func notFound(format string, args ...any) *APIError { return Errorf(http.StatusNotFound, format, args...) } func writeJSON(w http.ResponseWriter, status int, v Envelope) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } func writeOK(w http.ResponseWriter, data any) { writeJSON(w, http.StatusOK, Envelope{Code: 0, Msg: "ok", Data: data}) } func writeErr(w http.ResponseWriter, err error) { var apiErr *APIError if errors.As(err, &apiErr) { writeJSON(w, apiErr.Status, Envelope{Code: apiErr.Status, Msg: apiErr.Msg}) return } writeJSON(w, http.StatusInternalServerError, Envelope{Code: 500, Msg: err.Error()}) } // decodeJSON reads a bounded JSON body and rejects unknown fields. func decodeJSON(w http.ResponseWriter, r *http.Request, dst any, maxBytes int64) error { if maxBytes <= 0 { maxBytes = 1 << 20 } ct := r.Header.Get("Content-Type") if ct != "" && !strings.HasPrefix(ct, "application/json") { return Errorf(http.StatusUnsupportedMediaType, "请求必须使用 application/json") } r.Body = http.MaxBytesReader(w, r.Body, maxBytes) dec := json.NewDecoder(r.Body) dec.DisallowUnknownFields() if err := dec.Decode(dst); err != nil { if errors.Is(err, io.EOF) { return badRequest("请求体不能为空") } return badRequest("请求参数错误: %v", err) } if dec.More() { return badRequest("请求体只能包含一个 JSON 对象") } return nil }