github.com/zak-blake/goa@v1.4.1/middleware/timeout.go (about) 1 package middleware 2 3 import ( 4 "net/http" 5 "time" 6 7 "github.com/goadesign/goa" 8 9 "context" 10 ) 11 12 // Timeout sets a global timeout for all controller actions. 13 // The timeout notification is made through the context, it is the responsability of the request 14 // handler to handle it. For example: 15 // 16 // func (ctrl *Controller) DoLongRunningAction(ctx *DoLongRunningActionContext) error { 17 // action := NewLongRunning() // setup long running action 18 // c := make(chan error, 1) // create return channel 19 // go func() { c <- action.Run() } // Launch long running action goroutine 20 // select { 21 // case <- ctx.Done(): // timeout triggered 22 // action.Cancel() // cancel long running action 23 // <-c // wait for Run to return. 24 // return ctx.Err() // retrieve cancel reason 25 // case err := <-c: // action finished on time 26 // return err // forward its return value 27 // } 28 // } 29 // 30 // Controller actions can check if a timeout is set by calling the context Deadline method. 31 func Timeout(timeout time.Duration) goa.Middleware { 32 return func(h goa.Handler) goa.Handler { 33 return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { 34 nctx, cancel := context.WithTimeout(ctx, timeout) 35 defer cancel() 36 return h(nctx, rw, req) 37 } 38 } 39 }