qing6010
qing6010

Reputation: 109

How golang gin stop handler function immediately if connection is lost

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)?

Upvotes: 3

Views: 6502

Answers (1)

Peter
Peter

Reputation: 31751

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")
}

Upvotes: 8

Related Questions