Files
fn-serverless/examples/middleware/main.go
Travis Reeder b0494cd25d Boom, circle good to go, releases on commits to master too (#7)
* circle

* circle

* circle

* circle

* circle

* CIRCLE

* circle

* circle

* circle

* circle

* circle

* circle

* circle

* circle

* circle

* circle

* cijrcle

* circle

* circle

* circle

* circle

* c

* c

* circle

* testing release

* circle

* trying release

* c

* c

* functions: 0.3.25 release [skip ci]

* c

* functions: 0.3.26 release [skip ci]

* fn tool: 0.3.19 release [skip ci]

* testing cli release only

* fn tool: 0.3.20 release [skip ci]

* fn tool: 0.3.21 release [skip ci]

* hopefully the last thing

* fn tool: 0.3.22 release [skip ci]

* c

* fn tool: 0.3.23 release [skip ci]

* almost there....

* fn tool: 0.3.24 release [skip ci]

* fnlb: 0.0.2 release [skip ci]

* fn tool: 0.3.25 release [skip ci]

* fnlb: 0.0.3 release [skip ci]

* Added back in commented out lines.

* Fixing middleware example.
2017-07-26 17:38:37 -07:00

55 lines
1.3 KiB
Go

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) Chain(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(), "user", "I'm in!"))
next.ServeHTTP(w, r)
})
}