-
Notifications
You must be signed in to change notification settings - Fork 2
/
error.go
84 lines (73 loc) · 2.12 KB
/
error.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"log"
"net/http"
"sync/atomic"
"time"
"github.com/Knetic/govaluate"
)
type ErrorExpressionMiddleware struct {
expr *govaluate.EvaluableExpression
activeRequests uint32
serverStartTime time.Time
}
func NewErrorExpressionMiddleware(expression string) (*ErrorExpressionMiddleware, error) {
expr, err := govaluate.NewEvaluableExpressionWithFunctions(expression, expressionFunctions)
if err != nil {
return nil, fmt.Errorf("could not use expression: %s", err)
}
return &ErrorExpressionMiddleware{
expr: expr,
serverStartTime: time.Now(),
}, nil
}
func (em *ErrorExpressionMiddleware) WrapHTTP(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
atomic.AddUint32(&em.activeRequests, 1)
defer atomic.AddUint32(&em.activeRequests, ^uint32(0)) // decrement
errFn := func(err error) {
log.Println(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
parameters := &expressionParameters{
activeRequests: atomic.LoadUint32(&em.activeRequests),
t: time.Now().Sub(em.serverStartTime),
}
v, err := em.expr.Eval(parameters)
if err != nil {
errFn(fmt.Errorf("cannot evaluate mean expression: %s", err))
return
}
switch v := v.(type) {
case float64:
code := int(v)
rw.WriteHeader(code)
fmt.Fprintln(rw, http.StatusText(code))
case string:
switch v {
case "CLOSE":
hj, ok := rw.(http.Hijacker)
if !ok {
panic("connection not hijackable") // should never happen
}
conn, _, err := hj.Hijack()
if err != nil {
http.Error(rw, fmt.Sprintf("could not hijack connection: %s", err.Error()), http.StatusInternalServerError)
return
}
conn.Close() // drop connection
default:
errFn(fmt.Errorf("expression returned a string, '%s', but it was not recognized", v))
}
case bool:
if v {
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
} else {
next.ServeHTTP(rw, r)
}
default:
errFn(fmt.Errorf("expression did not return an expected type, returned: %T", v))
}
})
}