-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.go
46 lines (39 loc) · 1.18 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
40
41
42
43
44
45
46
package middleware
import (
. "github.com/warp-contracts/syncer/src/utils/logger"
"context"
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// Starts a separate goroutine to process the c.Next() callback
// If it returns within timeout does nothing
func HandleTimeout(timeout time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
// This context will stop pending operation after timeout, so it can free the resources
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
defer cancel()
c.Request = c.Request.WithContext(ctx)
// Capacity needs to be 1 to enable finishing after timeout,
// when no goroutine is listening
finish := make(chan struct{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
finish <- struct{}{}
}
}()
c.Next()
finish <- struct{}{}
}()
select {
case <-finish:
return
case <-ctx.Done():
// FIXME: When request is finished this way it'll most probably try to write to the connection after some time and panic.
err := errors.New("Request timed out")
LOGE(c, err, http.StatusServiceUnavailable).WithField("timeout", timeout).Error("Handling request took too long")
}
}
}