首页 > 解决方案 > 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)
    }

标签: gogo-gin

解决方案


推荐阅读