2

I am using gin-gonic/gin to write my server.

It seems even if the connection is lost, the handler function is still running. For example, if I visit http://127.0.0.1:8080/ping and close the browser suddenly, the screen will continue to print all the numbers.

package main

import (
    "github.com/gin-gonic/gin"
    "log"
    "time"
)

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        for i := 1; i < 15; i++ {
            time.Sleep(time.Second * 1)
            log.Println(i)
        }
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run("127.0.0.1:8080")
}

How should I stop handler function immediately (e.g. to reduce server load)?

David Buck
  • 3,752
  • 35
  • 31
  • 35
qing6010
  • 99
  • 3
  • 7

1 Answers1

7

The request context is canceled when the client disconnects, so simply check if c.Done() is ready to receive:

package main

import (
    "log"
    "time"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        t := time.NewTicker(1 * time.Second)
        defer t.Stop()

        for i := 1; i < 15; i++ {
            select {
            case <-t.C:
                log.Println(i)
            case <-c.Request.Context().Done():
                // client gave up
                return
            }
        }

        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run("127.0.0.1:8080")
}
Peter
  • 29,454
  • 5
  • 48
  • 60
  • I tested the code and it still prints out all the numbers though – qing6010 Nov 16 '18 at 05:54
  • 2
    OK... it works by replacing "c.Done()" with "c.Request.Context().Done()" as from https://github.com/gin-gonic/gin/issues/1452. – qing6010 Nov 16 '18 at 06:13
  • 1
    Sorry about that. I just assumed that gin's context behaves like the standard request context. I have updated the answer. – Peter Nov 16 '18 at 08:13