Files
2026-06-15 23:48:37 +08:00

57 lines
1.3 KiB
Go

package response
import (
"encoding/json"
"net/http"
)
type APIResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data"`
}
func JSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(APIResponse{
Code: 0,
Message: "success",
Data: data,
})
}
func Error(w http.ResponseWriter, status int, code int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(APIResponse{
Code: code,
Message: message,
Data: nil,
})
}
func BadRequest(w http.ResponseWriter, message string) {
Error(w, http.StatusBadRequest, 40001, message)
}
func Unauthorized(w http.ResponseWriter, message string) {
Error(w, http.StatusUnauthorized, 40101, message)
}
func Forbidden(w http.ResponseWriter, message string) {
Error(w, http.StatusForbidden, 40301, message)
}
func NotFound(w http.ResponseWriter, message string) {
Error(w, http.StatusNotFound, 40401, message)
}
func InternalError(w http.ResponseWriter, message string) {
Error(w, http.StatusInternalServerError, 50001, message)
}
func TooManyRequests(w http.ResponseWriter, message string) {
Error(w, http.StatusTooManyRequests, 42901, message)
}