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