With gin v1.8.0, gin.Context is canceled within goroutineย #3166
Closed
Description
Description
With gin v1.8.0, the gin.Context
is canceled when we use it within goroutine for doing async task (so this task can be executed after the reply to http client that doing request on gin router). This is big breaking change in regard of gin v1.7
How to reproduce
This test below is red with gin v1.8.0 but it was green with v1.7.7.
package main
import (
"log"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/gin-gonic/gin"
)
func TestGinContextCancel(t *testing.T) {
serv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
return
}))
defer serv.Close()
wg := &sync.WaitGroup{}
r := gin.New()
r.GET("/", func(ginctx *gin.Context) {
wg.Add(1)
ginctx = ginctx.Copy()
// start async goroutine for calling serv
go func() {
defer wg.Done()
req, err := http.NewRequestWithContext(ginctx, http.MethodGet, serv.URL, nil)
if err != nil {
panic(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
// context is always canceled with gin v1.8.0, it is big breaking change with gin v1.7
t.Error("context is always canceled with gin v1.8.0, it is big breaking change with gin v1.7", err)
return
}
if res.StatusCode != http.StatusOK {
log.Println("unexpected status code ", res.Status)
return
}
}()
})
go func() {
err := r.Run(":8080")
if err != nil {
panic(err)
}
}()
res, err := http.Get("http://127.1:8080/")
if err != nil {
panic(err)
}
if res.StatusCode != http.StatusOK {
panic(err)
}
wg.Wait()
}
Expectations
With gin v1.8.0, the provided test must be green
Actual result
With gin v1.8.0, the provided test is red
Environment
- go version: 1.18
- gin version (or commit ref): 1.8.0
- operating system: linux