コード例 #1
0
ファイル: httpctx_test.go プロジェクト: spkg/httpctx
func TestHandler(t *testing.T) {
	emptyFunc := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		return nil
	}
	for i, tc := range []struct {
		http.Handler
	}{
		{httpctx.HandleFunc(emptyFunc)},
		{httpctx.Use(middleware1).Use(middleware2).HandleFunc(emptyFunc)},
		{httpctx.Context(context.TODO()).Use(middleware2).HandleFunc(emptyFunc)},
	} {
		srv := httptest.NewServer(tc.Handler)
		resp, err := http.Get(srv.URL)
		srv.Close()
		resp.Body.Close()
		if err != nil {
			t.Errorf("%d. %v", i, err)
		}
	}
}
コード例 #2
0
ファイル: examples_test.go プロジェクト: spkg/httpctx
func ExampleContext() {
	ctx := context.Background()

	// Create a new context based on the background context.
	// For example, cancel on SIGINT and/or SIGTERM.
	ctx = makeNewContext(ctx)

	// Any call using the public stack will be passed ctx
	// instead of the background context for the handlers
	// in the stack.
	public := httpctx.Context(ctx).Use(ensureHttps)

	// Because authenticate is based on public, any call
	// using this stack will also be passed ctx instead
	// of the background context for handlers in the stack.
	authenticate := public.Use(authenticate, ensureAdmin)

	http.Handle("/admin", authenticate.HandleFunc(admin))
	http.Handle("/", public.HandleFunc(index))
	http.ListenAndServe(":8080", nil)
}