-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.go
More file actions
42 lines (36 loc) · 1.34 KB
/
timeout.go
File metadata and controls
42 lines (36 loc) · 1.34 KB
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
40
41
42
package rmhttp
import (
"net/http"
"time"
)
// ------------------------------------------------------------------------------------------------
// TIMEOUT
// ------------------------------------------------------------------------------------------------
// Timeout encapsulates a duration and message that should be used for applying timeouts to
// Route handlers, with a specific error message.
type Timeout struct {
Duration time.Duration
Message string
Enabled bool
}
// NewTimeout creates, initialises and returns a pointer to a Timeout.
func NewTimeout(duration time.Duration, message string) Timeout {
return Timeout{
Duration: duration,
Message: message,
Enabled: true,
}
}
// ------------------------------------------------------------------------------------------------
// TIMEOUT MIDDLEWARE
// ------------------------------------------------------------------------------------------------
// TimeoutMiddleware creates, initialises and returns a middleware function that will wrap the next
// handler in the stack with a timeout handler.
func TimeoutMiddleware(timeout Timeout) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
th := http.TimeoutHandler(next, timeout.Duration, timeout.Message)
th.ServeHTTP(w, r)
})
}
}