Saturday, May 4, 2024
HomeGolangTime Out Midlle Warein Gin-Golang-Suggestions Required - Code Overview

Time Out Midlle Warein Gin-Golang-Suggestions Required – Code Overview


Hello Go Specialists-Might you people please touch upon the implementation of a customized timeout middleware . I’m making a context with a deadline in my middleware and utilizing it in the remaining handlers for timeouts(to wrap the question to DB finally) and it’s working as anticipated. Lengthy story quick, I’m on the lookout for finest practices.I used to be questioning if any Go/Gin knowledgeable can weigh on the professionals/cons of the given strategy.

TimeOut Code-

func AddTimeOutMiddleware() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        ct, cancel := context.WithDeadline(ctx.Request.Context(), time.Now().Add((3 * time.Microsecond)))
        defer cancel()
        ctx.Set("workContext", ct)
        ctx.Subsequent()
        if ct.Err() != nil {

            ctx.JSON(int(http.DefaultClient.Timeout), "Request Timed Out")
        }
    }
}

Relaxation Handler Code-

func (athHan *AuthHandler) authenticateUser(ctx *gin.Context) {
    var authDetails Auth
    if err := ctx.ShouldBindJSON(&authDetails); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"error": "Please verify the required fields for Authentication"})
        return
    }
    c, _ := ctx.Get("workContext") //Get the deal with on context
    chCtx := c.(context.Context)   //
    rst := athHan.athSer.ValidateUserInRepo(chCtx, authDetails.UserName, authDetails.Password)
    if chCtx.Err() == nil {
        if rst {
            ctx.JSON(http.StatusOK, gin.H{"message": "Authentication Profitable"})
        } else if chCtx.Err() == nil {

            ctx.JSON(http.StatusOK, gin.H{"message": "Authentication Failure"})
        }

    }

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments