Goroutines inside a middleware
When starting new Goroutines inside a middleware or handler, you SHOULD NOT use the original context inside it, you have to use a read-only copy.
func main() {
app := iris.Default()
app.Get("/long_async", func(ctx iris.Context) {
// create a clone to be used inside the goroutine
ctxCopy := ctx.Clone()
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// note that you are using the copied context "ctxCopy", IMPORTANT
log.Printf("Done! in path: %s", ctxCopy.Path())
}()
})
app.Get("/long_sync", func(ctx iris.Context) {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// since we are NOT using a goroutine, we do not have to copy the context
log.Printf("Done! in path: %s", ctx.Path())
})
app.Listen(":8080")
}