/
middleware.go
51 lines (41 loc) · 1.07 KB
/
middleware.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
package langserver
import (
"github.com/x1unix/go-playground/pkg/goplay"
"net/http"
)
// HandlerFunc is langserver request handler
type HandlerFunc func(http.ResponseWriter, *http.Request) error
// GuardFn is guard middleware handler
type GuardFn func(r *http.Request) error
// WrapHandler wraps handler
func WrapHandler(h HandlerFunc, guards ...GuardFn) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if len(guards) == 0 {
for _, guardFn := range guards {
if err := guardFn(r); err != nil {
handleError(err, w)
return
}
}
}
handleError(h(w, r), w)
}
}
// ValidateContentLength validates Go code snippet size
func ValidateContentLength(r *http.Request) error {
if err := goplay.ValidateContentLength(int(r.ContentLength)); err != nil {
return NewHTTPError(http.StatusRequestEntityTooLarge, err)
}
return nil
}
func handleError(err error, w http.ResponseWriter) {
if err == nil {
return
}
if httpErr, ok := err.(*HTTPError); ok {
httpErr.WriteResponse(w)
return
}
resp := NewErrorResponse(err)
resp.Write(w)
}