예제 #1
0
// authenticate is an example of middleware that authenticates using basic authentication
func authenticate(h httpctx.Handler) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		credentials := r.Header.Get("WWW-Authenticate")
		ctx, err := checkCredentials(ctx, credentials)
		if err != nil {
			return err
		}
		return h.ServeHTTPContext(ctx, w, r)
	})
}
예제 #2
0
// ensureHttps is an example of middleware that ensures that the request scheme is https.
func ensureHttps(h httpctx.Handler) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		if r.URL.Scheme != "https" {
			u := *r.URL
			u.Scheme = "https"
			http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
			return nil
		}
		return h.ServeHTTPContext(ctx, w, r)
	})
}
예제 #3
0
func ensureAdmin(h httpctx.Handler) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		// ... get the userid from the context and ensure that the user has admin privilege ...
		return h.ServeHTTPContext(ctx, w, r)
	})
}
예제 #4
0
func middleware2(f httpctx.Handler) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		return nil
	})
}
예제 #5
0
	"testing"

	"github.com/spkg/httpctx"
	"github.com/stretchr/testify/assert"
	"golang.org/x/net/context"
)

func Test1(t *testing.T) {
	assert := assert.New(t)
	stack := httpctx.Use(middleware1, middleware2)
	assert.NotNil(stack)

	http.Handle("/api/whatever", stack.Handle(doWhateverHandler))
}

var doWhateverHandler = httpctx.HandlerFunc(doWhatever)

func doWhatever(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	return nil
}

func middleware1(f httpctx.Handler) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		return nil
	})
}

func middleware2(f httpctx.Handler) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		return nil
	})