This commit is contained in:
vipg
2026-02-09 16:59:04 +08:00
parent 611b3b307c
commit ec07824a4d
3 changed files with 72 additions and 22 deletions

View File

@@ -0,0 +1,12 @@
package codes
type Code string
const (
OK Code = "ok"
InvalidInput Code = "invalid_input"
Unauthorized Code = "unauthorized"
Conflict Code = "conflict"
InternalError Code = "internal_error"
MethodNotAllowed Code = "method_not_allowed"
)

View File

@@ -0,0 +1,43 @@
package httpx
import (
"encoding/json"
"net/http"
"common/types"
"common/codes"
)
func WriteJSON(w http.ResponseWriter, status int, ok bool, msg string, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(types.Response{Status: ok, Message: msg, Data: data})
}
func OK(w http.ResponseWriter, data interface{}) {
WriteJSON(w, http.StatusOK, true, string(codes.OK), data)
}
func Created(w http.ResponseWriter, data interface{}) {
WriteJSON(w, http.StatusCreated, true, string(codes.OK), data)
}
func BadRequest(w http.ResponseWriter, msg string) {
WriteJSON(w, http.StatusBadRequest, false, msg, map[string]string{"code": string(codes.InvalidInput)})
}
func Unauthorized(w http.ResponseWriter, msg string) {
WriteJSON(w, http.StatusUnauthorized, false, msg, map[string]string{"code": string(codes.Unauthorized)})
}
func Conflict(w http.ResponseWriter, msg string) {
WriteJSON(w, http.StatusConflict, false, msg, map[string]string{"code": string(codes.Conflict)})
}
func MethodNotAllowed(w http.ResponseWriter, msg string) {
WriteJSON(w, http.StatusMethodNotAllowed, false, msg, map[string]string{"code": string(codes.MethodNotAllowed)})
}
func InternalError(w http.ResponseWriter) {
WriteJSON(w, http.StatusInternalServerError, false, string(codes.InternalError), map[string]string{"code": string(codes.InternalError)})
}