go - GoLang 使用 gin 调用函数而不传递 gin.Context
问题描述
我遇到了一个场景
func main (c *gin.Context){
if err := g.Bind(&data); err != nil {
log.Fatalln(err)
helper.TraceLog(err)
helper.Fail(c, helper.INPUT_PARAMS_ERROR, "", err)
return
}
}
func Fail(c *gin.Context, errorCode string, result string, message interface{}) {
response := Response{}
response.Code = errorCode
response.Result = message
response.Message = result
json.Marshal(response)
c.JSON(http.StatusBadRequest, response)
}
是否有可能我不必将 gin 传递给 Fail func?我已经尝试了所有我能想到的解决方案,但没有任何效果。
我这样做的原因是让代码看起来更简单和干净。
我正在寻找的是这样的:
func main (c *gin.Context){
if err := g.Bind(&data); err != nil {
log.Fatalln(err)
helper.TraceLog(err)
helper.Fail(helper.INPUT_PARAMS_ERROR, "", err)
return
}
}
func Fail(errorCode string, result string, message interface{}) {
var c *gin.Context
response := Response{}
response.Code = errorCode
response.Result = message
response.Message = result
json.Marshal(response)
c.JSON(http.StatusBadRequest, response)
}
解决方案
推荐阅读
- linux - RPC:如何在 macOS 上退出 svc_run()?
- css - 我怎样才能使背景图像固定
- mongodb - MongoDB Atlas 搜索定义 JSON - 字符串数组
- mongodb - Spring Boot按多个字段过滤(MongoDB)
- mysql - Power BI Gateway - MySQL 源不支持加密连接
- swift - '测量类型的值
'没有成员'格式化' - mongodb - oplog.rs 的 MongoDB mongodump 查询
- c# - 我有 checklistBox,我想获取所选项目的 valuememebr 并显示成员 c#
- maven-shade-plugin - 如何排除被搬迁?
- ios - Objective C 中某些 iPhone 中的 Double 到 String 转换问题