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.

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/long_async", func(c *gin.Context) {
  4. // create copy to be used inside the goroutine
  5. cCp := c.Copy()
  6. go func() {
  7. // simulate a long task with time.Sleep(). 5 seconds
  8. time.Sleep(5 * time.Second)
  9. // note that you are using the copied context "cCp", IMPORTANT
  10. log.Println("Done! in path " + cCp.Request.URL.Path)
  11. }()
  12. })
  13. r.GET("/long_sync", func(c *gin.Context) {
  14. // simulate a long task with time.Sleep(). 5 seconds
  15. time.Sleep(5 * time.Second)
  16. // since we are NOT using a goroutine, we do not have to copy the context
  17. log.Println("Done! in path " + c.Request.URL.Path)
  18. })
  19. // Listen and serve on 0.0.0.0:8080
  20. r.Run(":8080")
  21. }