This is an implementation of a custom timeout middleware.

I am creating a context with a deadline in my middleware and using it in the rest handlers for timeouts (to wrap the query to DB eventually) and it is working as expected. Long story short, I am looking for best practices. I was wondering if any Go/Gin expert can weigh on the pros/cons of the given approach.

Timeout Code(middleware 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)
        if ct.Err() != nil {

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

Rest 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 check the required fields for Authentication"})
    c, _ := ctx.Get("workContext") //Get the handle 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 Successful"})
        } else if chCtx.Err() == nil {

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




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.