-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware.go
40 lines (35 loc) · 970 Bytes
/
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
package middleware
import (
"fmt"
"net/http"
"github.com/diy-cloud/lux/context"
)
type Set struct {
Request func(*http.Request) (*http.Request, int)
Response func(*context.LuxContext) (*context.LuxContext, error)
}
func ApplyRequests(ctx *context.LuxContext, middlewares []Set) string {
for _, m := range middlewares {
if m.Request == nil {
continue
}
_, code := m.Request(ctx.Request)
if 400 <= code && code < 600 {
ctx.Response.WriteHeader(code)
return fmt.Sprintf("Middleware Request Reading %s: %s from %s", ctx.Request.URL.Path, http.StatusText(code), ctx.Request.RemoteAddr)
}
}
return ""
}
func ApplyResponses(ctx *context.LuxContext, middlewares []Set) string {
for _, m := range middlewares {
if m.Response == nil {
continue
}
_, err := m.Response(ctx)
if err != nil {
return fmt.Sprintf("Middleware Response Writing %s: %s from %s", ctx.Request.URL.Path, err.Error(), ctx.Request.RemoteAddr)
}
}
return ""
}