Esempio n. 1
0
func TestAdapters(t *testing.T) {

	hndlr := ctxhttp.Chain(
		h1{},
		ctxhttp.WithXHTTPMethodOverride(),
		ctxhttp.WithHeader("X-Men", "Y-Women"),
	)

	w := httptest.NewRecorder()
	req, err := http.NewRequest(httputils.MethodGet, "http://example.com/foo", nil)
	req.Header.Set(httputils.MethodOverrideHeader, httputils.MethodPut)
	assert.NoError(t, err)

	a := ctxhttp.NewAdapter(context.Background(), hndlr)
	a.ServeHTTP(w, req)

	assert.Equal(t, httputils.MethodPut, req.Method)
	assert.Equal(t, "h1 called", w.Body.String())
	assert.Equal(t, "Y-Women", w.Header().Get("X-Men"))
}
func ExampleWithInitStoreByToken() {
	initStore()
	ctx := store.NewContextReader(context.Background(), testStoreService)

	jwtService, err := ctxjwt.NewService(ctxjwt.WithPassword([]byte(`GÒph3r`)))

	finalHandler := ctxhttp.Chain(
		ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			_, haveReqStore, err := store.FromContextReader(ctx)
			if err != nil {
				return err
			}
			// now we know that the current request depends on the store view DE.
			fmt.Fprintf(w, "StoreCode: %s\n", haveReqStore.StoreCode())
			return nil
		}), // 								  executed 3rd
		store.WithInitStoreByToken(),      // executed 2nd
		jwtService.WithParseAndValidate(), // executed 1st
	)

	ts := httptest.NewServer(ctxhttp.NewAdapter(ctx, finalHandler))
	defer ts.Close()

	// Setup GET request
	token, _, err := jwtService.GenerateToken(
		map[string]interface{}{
			// Despite default store for Website ID 1 is AT we are currently
			// in the store context of DE.
			store.ParamName: "de",
		},
	)
	if err != nil {
		log.Fatal("jwtService.GenerateToken", "err", err)
	}

	req, err := http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		log.Fatal("http.Get", "err", err)
	}
	ctxjwt.SetHeaderAuthorization(req, token)

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal("http.DefaultClient.Do", "err", err)
	}

	response, err := ioutil.ReadAll(res.Body)
	if errC := res.Body.Close(); errC != nil {
		log.Fatal("res.Body.Close", "err", errC)
	}

	if err != nil {
		log.Fatal("ioutil.ReadAll", "err", err)
	}

	fmt.Printf("Response: %s\n", response)
	fmt.Printf("Log: %s\n", testDebugLogBuf.String())
	// Output:
	// Response: StoreCode: de
	//
	// Log:
}