Files
sundynix-micro-be/common/response/response.go
T
2026-04-27 00:02:18 +08:00

68 lines
1.6 KiB
Go

package response
import (
"encoding/json"
"net/http"
)
// Body 统一响应体
type Body struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
}
func writeJSON(w http.ResponseWriter, body *Body) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(body)
}
// OkWithData 成功响应(带数据)
func OkWithData(w http.ResponseWriter, data interface{}) {
writeJSON(w, &Body{Code: 200, Msg: "success", Data: data})
}
// Ok 成功响应(无数据)
func Ok(w http.ResponseWriter) {
writeJSON(w, &Body{Code: 200, Msg: "success"})
}
// OkWithMsg 成功响应(自定义消息)
func OkWithMsg(w http.ResponseWriter, msg string) {
writeJSON(w, &Body{Code: 200, Msg: msg})
}
// Fail 失败响应
func Fail(w http.ResponseWriter, msg string) {
writeJSON(w, &Body{Code: 400, Msg: msg})
}
// FailWithCode 失败响应(自定义错误码)
func FailWithCode(w http.ResponseWriter, code int, msg string) {
writeJSON(w, &Body{Code: code, Msg: msg})
}
// NoAuth 未授权响应
func NoAuth(w http.ResponseWriter, msg string) {
writeJSON(w, &Body{Code: 401, Msg: msg})
}
// PageResult 分页结果
type PageResult struct {
List interface{} `json:"list"`
Total int64 `json:"total"`
Current int `json:"current"`
Size int `json:"size"`
}
// OkWithPage 分页成功响应
func OkWithPage(w http.ResponseWriter, list interface{}, total int64, current, size int) {
OkWithData(w, PageResult{
List: list,
Total: total,
Current: current,
Size: size,
})
}