miaopanel
1package httpapi
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io"
8 "net/http"
9 "strings"
10)
11
12// Envelope is the single response shape of the panel API.
13type Envelope struct {
14 Code int `json:"code"`
15 Msg string `json:"msg"`
16 Data any `json:"data,omitempty"`
17}
18
19// APIError carries an HTTP status and a user facing message.
20type APIError struct {
21 Status int
22 Msg string
23}
24
25func (e *APIError) Error() string { return e.Msg }
26
27// Errorf builds an APIError.
28func Errorf(status int, format string, args ...any) *APIError {
29 return &APIError{Status: status, Msg: fmt.Sprintf(format, args...)}
30}
31
32func badRequest(format string, args ...any) *APIError {
33 return Errorf(http.StatusBadRequest, format, args...)
34}
35
36func notFound(format string, args ...any) *APIError {
37 return Errorf(http.StatusNotFound, format, args...)
38}
39
40func writeJSON(w http.ResponseWriter, status int, v Envelope) {
41 w.Header().Set("Content-Type", "application/json; charset=utf-8")
42 w.Header().Set("Cache-Control", "no-store")
43 w.WriteHeader(status)
44 _ = json.NewEncoder(w).Encode(v)
45}
46
47func writeOK(w http.ResponseWriter, data any) {
48 writeJSON(w, http.StatusOK, Envelope{Code: 0, Msg: "ok", Data: data})
49}
50
51func writeErr(w http.ResponseWriter, err error) {
52 var apiErr *APIError
53 if errors.As(err, &apiErr) {
54 writeJSON(w, apiErr.Status, Envelope{Code: apiErr.Status, Msg: apiErr.Msg})
55 return
56 }
57 writeJSON(w, http.StatusInternalServerError, Envelope{Code: 500, Msg: err.Error()})
58}
59
60// decodeJSON reads a bounded JSON body and rejects unknown fields.
61func decodeJSON(w http.ResponseWriter, r *http.Request, dst any, maxBytes int64) error {
62 if maxBytes <= 0 {
63 maxBytes = 1 << 20
64 }
65 ct := r.Header.Get("Content-Type")
66 if ct != "" && !strings.HasPrefix(ct, "application/json") {
67 return Errorf(http.StatusUnsupportedMediaType, "请求必须使用 application/json")
68 }
69 r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
70 dec := json.NewDecoder(r.Body)
71 dec.DisallowUnknownFields()
72 if err := dec.Decode(dst); err != nil {
73 if errors.Is(err, io.EOF) {
74 return badRequest("请求体不能为空")
75 }
76 return badRequest("请求参数错误: %v", err)
77 }
78 if dec.More() {
79 return badRequest("请求体只能包含一个 JSON 对象")
80 }
81 return nil
82}