first commit
This commit is contained in:
69
pkg/response/response.go
Normal file
69
pkg/response/response.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// 定义通用的响应结构
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// 定义分页响应结构
|
||||
type PageResult struct {
|
||||
List interface{} `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
}
|
||||
|
||||
// 响应成功
|
||||
func Success(w http.ResponseWriter, data interface{}) {
|
||||
result := Response{
|
||||
Code: http.StatusOK,
|
||||
Data: data,
|
||||
Message: "操作成功",
|
||||
}
|
||||
httpx.OkJson(w, result)
|
||||
}
|
||||
|
||||
// 响应失败
|
||||
func Fail(w http.ResponseWriter, code int, message string) {
|
||||
result := Response{
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
httpx.WriteJson(w, code, result)
|
||||
}
|
||||
|
||||
// 无权限
|
||||
func Unauthorized(w http.ResponseWriter, message string) {
|
||||
result := Response{
|
||||
Code: http.StatusUnauthorized,
|
||||
Message: message,
|
||||
}
|
||||
httpx.WriteJson(w, http.StatusUnauthorized, result)
|
||||
}
|
||||
|
||||
// 响应分页数据
|
||||
func Page(w http.ResponseWriter, list interface{}, total int64, page int, pageSize int) {
|
||||
result := Response{
|
||||
Code: http.StatusOK,
|
||||
Data: PageResult{List: list, Total: total, Page: page, PageSize: pageSize},
|
||||
Message: "查询成功",
|
||||
}
|
||||
httpx.OkJson(w, result)
|
||||
}
|
||||
|
||||
// 自定义错误响应
|
||||
func CustomError(w http.ResponseWriter, code int, message string, data interface{}) {
|
||||
result := Response{
|
||||
Code: code,
|
||||
Data: data,
|
||||
Message: message,
|
||||
}
|
||||
httpx.WriteJson(w, code, result)
|
||||
}
|
||||
Reference in New Issue
Block a user