Files
go-common/http/response.go

106 lines
3.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package http
import (
"encoding/json"
"net/http"
"time"
)
// Response 标准响应结构
type Response struct {
Code int `json:"code"` // 业务状态码0表示成功
Message string `json:"message"` // 响应消息
Timestamp int64 `json:"timestamp"` // 时间戳
Data interface{} `json:"data"` // 响应数据
}
// PageResponse 分页响应结构
type PageResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
Data *PageData `json:"data"`
}
// PageData 分页数据
type PageData struct {
List interface{} `json:"list"` // 数据列表
Total int64 `json:"total"` // 总记录数
Page int `json:"page"` // 当前页码
PageSize int `json:"pageSize"` // 每页大小
}
// writeJSON 写入JSON响应公共方法
// httpCode: HTTP状态码200表示正常500表示系统错误等
// code: 业务状态码0表示成功非0表示业务错误
// message: 响应消息
// data: 响应数据
func writeJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(httpCode)
response := Response{
Code: code,
Message: message,
Timestamp: time.Now().Unix(),
Data: data,
}
json.NewEncoder(w).Encode(response)
}
// Success 成功响应(公共方法)
// w: ResponseWriter
// data: 响应数据可以为nil
// message: 响应消息(可选),如果为空则使用默认消息 "success"
//
// 使用方式:
//
// Success(w, data) // 只有数据,使用默认消息 "success"
// Success(w, data, "查询成功") // 数据+消息
func Success(w http.ResponseWriter, data interface{}, message ...string) {
msg := "success"
if len(message) > 0 && message[0] != "" {
msg = message[0]
}
writeJSON(w, http.StatusOK, 0, msg, data)
}
// SuccessPage 分页成功响应(公共方法)
// w: ResponseWriter
// list: 数据列表
// total: 总记录数
// page: 当前页码
// pageSize: 每页大小
// message: 响应消息(可选),如果为空则使用默认消息 "success"
func SuccessPage(w http.ResponseWriter, list interface{}, total int64, page, pageSize int, message ...string) {
msg := "success"
if len(message) > 0 && message[0] != "" {
msg = message[0]
}
pageData := &PageData{
List: list,
Total: total,
Page: page,
PageSize: pageSize,
}
writeJSON(w, http.StatusOK, 0, msg, pageData)
}
// Error 错误响应(公共方法)
// w: ResponseWriter
// code: 业务错误码非0表示业务错误
// message: 错误消息
func Error(w http.ResponseWriter, code int, message string) {
writeJSON(w, http.StatusOK, code, message, nil)
}
// SystemError 系统错误响应返回HTTP 500公共方法
// w: ResponseWriter
// message: 错误消息
func SystemError(w http.ResponseWriter, message string) {
writeJSON(w, http.StatusInternalServerError, 500, message, nil)
}