-
Notifications
You must be signed in to change notification settings - Fork 53
/
timeout.go
47 lines (41 loc) · 821 Bytes
/
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
40
41
42
43
44
45
46
47
/*
* @Author: seekwe
* @Date: 2019-05-29 15:08:41
* @Last Modified by: seekwe
* @Last Modified time: 2019-05-29 17:08:04
*/
package timeout
import (
"bytes"
"context"
"net/http"
"time"
"github.com/sohaha/zlsgo/znet"
)
type (
bodyWriter struct {
http.ResponseWriter
body *bytes.Buffer
}
)
func (w bodyWriter) Write(b []byte) (int, error) {
return w.body.Write(b)
}
func New(waitingTime time.Duration, custom ...znet.HandlerFunc) znet.HandlerFunc {
return func(c *znet.Context) {
ctx, _ := context.WithTimeout(c.Request.Context(), waitingTime)
finish := make(chan struct{}, 1)
go func(c *znet.Context) {
c.Next()
finish <- struct{}{}
}(c)
select {
case <-finish:
case <-ctx.Done():
c.Abort(http.StatusGatewayTimeout)
if len(custom) > 0 {
custom[0](c)
}
}
}
}