Use chi style middle ware

This commit is contained in:
James Jeffrey
2017-07-19 13:44:26 -07:00
committed by Travis Reeder
parent 570e9265f1
commit cf2c3cf404
21 changed files with 192 additions and 240 deletions

View File

@@ -3,13 +3,11 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"gitlab-odx.oracle.com/odx/functions/api/models"
"gitlab-odx.oracle.com/odx/functions/api/server"
)
@@ -18,13 +16,15 @@ func main() {
funcServer := server.NewFromEnv(ctx)
funcServer.AddMiddlewareFunc(func(ctx server.MiddlewareContext, w http.ResponseWriter, r *http.Request, app *models.App) error {
start := time.Now()
fmt.Println("CustomMiddlewareFunc called at:", start)
ctx.Next()
fmt.Println("Duration:", (time.Now().Sub(start)))
return nil
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)
@@ -33,20 +33,22 @@ func main() {
type CustomMiddleware struct {
}
func (h *CustomMiddleware) Serve(ctx server.MiddlewareContext, w http.ResponseWriter, r *http.Request, app *models.App) error {
fmt.Println("CustomMiddleware called")
func (h *CustomMiddleware) Serve(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 errors.New("Invalid authorization token.")
}
fmt.Println("auth succeeded!")
ctx.Set("user", "I'm in!")
return nil
// 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)
})
}