-
Notifications
You must be signed in to change notification settings - Fork 405
/
main.go
55 lines (44 loc) · 1.37 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/fnproject/fn/api/server"
)
func main() {
ctx := context.Background()
funcServer := server.NewFromEnv(ctx)
funcServer.AddMiddlewareFunc(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
fmt.Println("CustomMiddlewareFunc called at:", start)
next.ServeHTTP(w, r)
fmt.Println("Duration:", (time.Now().Sub(start)))
})
})
funcServer.AddMiddleware(&customMiddleware{})
funcServer.Start(ctx)
}
type customMiddleware struct{}
func (h *customMiddleware) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("CustomMiddleware called")
// check auth header
tokenHeader := strings.SplitN(r.Header.Get("Authorization"), " ", 3)
if len(tokenHeader) < 2 || tokenHeader[1] != "KlaatuBaradaNikto" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
m2 := map[string]string{"message": "Invalid Authorization token."}
m := map[string]map[string]string{"error": m2}
json.NewEncoder(w).Encode(m)
return
}
fmt.Println("auth succeeded!")
r = r.WithContext(context.WithValue(r.Context(), contextKey("user"), "I'm in!"))
next.ServeHTTP(w, r)
})
}
type contextKey string