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. app := iris.Default()
  3. app.Get("/long_async", func(ctx iris.Context) {
  4. // create a clone to be used inside the goroutine
  5. ctxCopy := ctx.Clone()
  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 "ctxCopy", IMPORTANT
  10. log.Printf("Done! in path: %s", ctxCopy.Path())
  11. }()
  12. })
  13. app.Get("/long_sync", func(ctx iris.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.Printf("Done! in path: %s", ctx.Path())
  18. })
  19. app.Listen(":8080")
  20. }