Search code examples
gotimeoutgo-gin

Why I get socket hang up on Postman and 502 in nginX while Gin-Gonic has returned StatusOk on both scenarios?


Just to simplify my question I have a long running route that could take up to 2 minutes to return response. Now this is my sample http handler:

func GetHealth(svc *service.Hotel) gin.HandlerFunc {
   return func(c *gin.Context) {
      time.Sleep(30 * time.Second)
      c.JSON(200, gin.H{})
   }
}

Now when I call [GET] /health route postman returns Error: socket hang up at the exact time of returning response from gin-gonic which is logged 200 Ok:

[GIN] 2024/01/24 - 11:10:58 | 200 | 30.084587215s | ::1 | GET "/health"

Now the same project that goes as a reverse proxy behind nginX, I get 502 nginX error on API response while my service has logged 200 Ok .

The question is why I get error on client side while gin-gonic has successfully returned a response? How should I solve this problem?

enter image description here

I used github.com/gin-contrib/timeout library as I thought it is related to timeout of the route, but with no success.


Solution

  • In gin-gonic you can set WriteTimeout on your http.Server in order to prevent socket hang up or nginx 502.

    The interesting part is that it always logs 200 even if timeout exceeds, but client gets the error:

    srv := &http.Server{
            Addr: ":9000",
            // Good practice to set timeouts to avoid Slowloris attacks.
            WriteTimeout: time.Second * 120, // THIS TIMEOUT NEEDS TO BE SET
            ReadTimeout:  time.Second * 15,
            IdleTimeout:  time.Second * 60,
            Handler:      router,
        }