MCPcopy Create free account
hub / github.com/Prejudice-Studio/Twilight / writeJSONWithCode

Function writeJSONWithCode

internal/api/response.go:24–45  ·  view source on GitHub ↗

writeJSONWithCode 在 writeJSON 基础上允许传入业务级 error_code(见 errcode.go)。 当 errorCode 为空时回落到按 HTTP status 自动推导(defaultErrorCode)。

(w http.ResponseWriter, status int, success bool, errorCode, message string, data any)

Source from the content-addressed store, hash-verified

22// writeJSONWithCode 在 writeJSON 基础上允许传入业务级 error_code(见 errcode.go)。
23// 当 errorCode 为空时回落到按 HTTP status 自动推导(defaultErrorCode)。
24func writeJSONWithCode(w http.ResponseWriter, status int, success bool, errorCode, message string, data any) {
25 w.Header().Set("Content-Type", "application/json; charset=utf-8")
26 if w.Header().Get("Cache-Control") == "" {
27 w.Header().Set("Cache-Control", "no-store, private")
28 }
29 if w.Header().Get("Pragma") == "" {
30 w.Header().Set("Pragma", "no-cache")
31 }
32 w.WriteHeader(status)
33 resolvedCode := errorCode
34 if resolvedCode == "" {
35 resolvedCode = defaultErrorCode(status, success)
36 }
37 _ = json.NewEncoder(w).Encode(envelope{
38 Success: success,
39 Code: status,
40 ErrorCode: resolvedCode,
41 Message: message,
42 Data: data,
43 Timestamp: time.Now().Unix(),
44 })
45}
46
47// statusToErrorCode 把 HTTP status 直接映射到协议层 ErrCode。
48// 历史实现是一连串 case 字面量,每加一个 status 就要改一处 switch;

Callers 4

writeJSONFunction · 0.85
failWithCodeFunction · 0.85
failWithCodeDataFunction · 0.85

Calls 3

defaultErrorCodeFunction · 0.85
WriteHeaderMethod · 0.80
GetMethod · 0.45

Tested by

no test coverage detected