增加ctx.JSON的平替方法

This commit is contained in:
白茶清欢 2023-02-15 14:52:49 +08:00
parent 77d2310b27
commit 25aab2e8db
1 changed files with 26 additions and 0 deletions

View File

@ -17,6 +17,11 @@ import (
"github.com/gin-gonic/gin"
)
const (
// hasSendResponseFlag 已经发送响应数据的标识, 一旦识别到, 重复调用不会执行
hasSendResponseFlag = "GIN_PKG_HAS_SEND_RESPONSE"
)
// Success 成功的响应
//
// Author : go_developer@163.com<白茶清欢>
@ -33,6 +38,12 @@ func Success(ctx *gin.Context, data interface{}) {
//
// Date : 22:40 2022/6/25
func Send(ctx *gin.Context, code interface{}, httpCode int, data interface{}) {
if ctx.GetBool(hasSendResponseFlag) {
// 已经发送过数据, 后面在发送数据, 不执行
return
}
// 设置数据已发送的标识
defer ctx.Set(hasSendResponseFlag, true)
finishRequestTime := time.Now().UnixNano()
responseData := map[string]interface{}{
define.ResponseCodeField: code,
@ -75,3 +86,18 @@ func SendWithException(ctx *gin.Context, e exception.IException, data interface{
Send(ctx, e.GetCode(), e.GetHttpCode(), data)
}
}
// JSON ctx.JSON 的平替, 增加了数据是否已相应的标识
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:51 2023/2/15
func JSON(ctx *gin.Context, httpCode int, data interface{}) {
if ctx.GetBool(hasSendResponseFlag) {
// 已经发送过数据, 后面在发送数据, 不执行
return
}
// 设置数据已发送的标识
defer ctx.Set(hasSendResponseFlag, true)
ctx.JSON(httpCode, data)
}