Files
codexautopool/backend/internal/api/http.go

69 lines
1.7 KiB
Go

package api
import (
"encoding/json"
"net/http"
"codex-pool/internal/config"
)
// Result 统一 API 响应
type Result struct {
Code int `json:"code"`
Message string `json:"message,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// JSON 发送 JSON 响应
func JSON(w http.ResponseWriter, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(data)
}
// Success 发送成功响应
func Success(w http.ResponseWriter, data interface{}) {
JSON(w, http.StatusOK, Result{Code: 0, Data: data})
}
// Error 发送错误响应
func Error(w http.ResponseWriter, httpCode int, message string) {
JSON(w, httpCode, Result{Code: -1, Message: message})
}
// CORS 跨域中间件
func CORS(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
origin := "*"
if config.Global != nil && config.Global.CorsOrigin != "" {
origin = config.Global.CorsOrigin
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Api-Key")
w.Header().Set("Access-Control-Max-Age", "86400")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next(w, r)
}
}
// decodeJSON 解析 JSON 响应体
func decodeJSON(body interface{}, v interface{}) error {
switch b := body.(type) {
case []byte:
return json.Unmarshal(b, v)
default:
// 假设是 io.Reader
if reader, ok := body.(interface{ Read([]byte) (int, error) }); ok {
return json.NewDecoder(reader).Decode(v)
}
return json.Unmarshal(body.([]byte), v)
}
}