gin/response/response.go

71 lines
2.0 KiB
Go
Raw Normal View History

2022-06-25 23:03:46 +08:00
// Package response ...
//
// Description : response ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-06-25 20:52
package response
import (
"net/http"
"time"
"git.zhangdeman.cn/zhangdeman/exception"
"git.zhangdeman.cn/zhangdeman/gin/define"
"github.com/gin-gonic/gin"
)
// Success 成功的响应
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 22:37 2022/6/25
2022-06-26 13:33:03 +08:00
func Success(ctx *gin.Context, data interface{}) {
2022-06-25 23:03:46 +08:00
successException := exception.NewSuccess(data)
Send(ctx, successException.GetCode(), successException.GetHttpCode(), successException.GetData())
}
// Send 基础的发送数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 22:40 2022/6/25
2022-06-26 13:03:41 +08:00
func Send(ctx *gin.Context, code interface{}, httpCode int, data interface{}) {
2022-06-25 23:03:46 +08:00
responseData := map[string]interface{}{
2022-06-26 13:03:41 +08:00
define.ResponseCodeField: code,
define.ResponseMessageField: exception.GetMessage(code),
2022-06-25 23:03:46 +08:00
define.ResponseTraceIDField: ctx.GetString(define.TraceIDField),
define.ResponseRequestIDField: ctx.GetString(define.RequestIDField),
define.ResponseDataField: data,
2022-07-15 00:05:26 +08:00
define.HandleRequestCostField: float64(time.Now().UnixNano()-ctx.GetInt64(define.StartRequestTimeField)) / 1e9,
2022-06-25 23:03:46 +08:00
}
2022-06-26 13:03:41 +08:00
responseException := exception.New(code, httpCode, responseData)
2022-06-25 23:03:46 +08:00
ctx.JSON(responseException.GetHttpCode(), responseException.GetData())
}
// SendWithStatusOK ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 22:41 2022/6/25
func SendWithStatusOK(ctx *gin.Context, code interface{}, data map[string]interface{}) {
Send(ctx, code, http.StatusOK, data)
}
2022-06-26 13:28:31 +08:00
// SendWithException 使用exception发送数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 13:08 2022/6/26
2022-07-03 13:12:10 +08:00
func SendWithException(ctx *gin.Context, e exception.IException, data interface{}) {
2022-06-26 13:28:31 +08:00
if nil == e {
e = exception.NewSuccess(data)
}
if nil != e.GetData() {
Send(ctx, e.GetCode(), e.GetHttpCode(), e.GetData())
} else {
Send(ctx, e.GetCode(), e.GetHttpCode(), data)
}
}