38 lines
859 B
Go
38 lines
859 B
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
// writeJSON 写 JSON 响应。
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
// errDetail 构造 {"detail": msg} 错误体(与 Python FastAPI 默认错误格式一致)。
|
|
func errDetail(msg string) map[string]any {
|
|
return map[string]any{"detail": msg}
|
|
}
|
|
|
|
// writeErr 写错误响应。
|
|
func writeErr(w http.ResponseWriter, status int, msg string) {
|
|
writeJSON(w, status, errDetail(msg))
|
|
}
|
|
|
|
// decodeJSON 解析请求体 JSON。
|
|
func decodeJSON(r *http.Request, v any) error {
|
|
dec := json.NewDecoder(r.Body)
|
|
return dec.Decode(v)
|
|
}
|
|
|
|
// fallback 空字符串返回默认值。
|
|
func fallback(s, def string) string {
|
|
if s == "" {
|
|
return def
|
|
}
|
|
return s
|
|
}
|