Files
trading_assistant/trading_assistant_api/common/httpx/httpx.go
2026-02-09 17:59:34 +08:00

56 lines
1.8 KiB
Go

package httpx
import (
"encoding/json"
"net/http"
"common/types"
"common/codes"
)
func WriteJSON(w http.ResponseWriter, status int, ok bool, code int, msg string, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(types.Response{Status: ok, Message: msg, Code: code, Data: data})
}
func OK(w http.ResponseWriter, r *http.Request, data interface{}) {
WriteJSON(w, http.StatusOK, true, codes.ValueOK, string(codes.OK), addRequestID(r, data))
}
func Created(w http.ResponseWriter, r *http.Request, data interface{}) {
WriteJSON(w, http.StatusCreated, true, codes.ValueOK, string(codes.OK), addRequestID(r, data))
}
func BadRequest(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusBadRequest, false, codes.ValueInvalidInput, msg, addRequestID(r, nil))
}
func Unauthorized(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusUnauthorized, false, codes.ValueUnauthorized, msg, addRequestID(r, nil))
}
func Conflict(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusConflict, false, codes.ValueConflict, msg, addRequestID(r, nil))
}
func MethodNotAllowed(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusMethodNotAllowed, false, codes.ValueMethodNotAllowed, msg, addRequestID(r, nil))
}
func InternalError(w http.ResponseWriter, r *http.Request) {
WriteJSON(w, http.StatusInternalServerError, false, codes.ValueInternalError, string(codes.InternalError), addRequestID(r, nil))
}
func addRequestID(r *http.Request, data interface{}) interface{} {
rid := RequestIDFromContext(r)
if m, ok := data.(map[string]string); ok {
m["request_id"] = rid
return m
}
if data == nil {
return map[string]string{"request_id": rid}
}
return map[string]interface{}{"request_id": rid, "data": data}
}