package towel_test import ( "fmt" "net/http" "net/http/httptest" "git.golem15.com/golem15/summercms/modules/towel" ) // withAcmeScope tags every request with the organization and collection it serves. func withAcmeScope(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := towel.WithOrganization(r.Context(), "acme") ctx = towel.WithCollection(ctx, "blog") next.ServeHTTP(w, r.WithContext(ctx)) }) } func listPosts(w http.ResponseWriter, r *http.Request) { org, _ := towel.Organization(r.Context()) locale, ok := towel.Locale(r.Context()) if !ok { locale = "en" } fmt.Fprintf(w, "posts for %s in %s\n", org, locale) } func ExampleWithLocale() { // surf sets the locale from Accept-Language; here the test sets it. req := httptest.NewRequest(http.MethodGet, "/api/blog/posts", nil) req = req.WithContext(towel.WithLocale(req.Context(), "pl")) rec := httptest.NewRecorder() withAcmeScope(http.HandlerFunc(listPosts)).ServeHTTP(rec, req) fmt.Print(rec.Body.String()) // Without a locale the handler falls back to English. rec = httptest.NewRecorder() withAcmeScope(http.HandlerFunc(listPosts)).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/blog/posts", nil)) fmt.Print(rec.Body.String()) // Output: // posts for acme in pl // posts for acme in en } // ExampleWithCollection reads the collection withAcmeScope stores. func ExampleWithCollection() { var collection string withAcmeScope(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { collection, _ = towel.Collection(r.Context()) })).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) fmt.Println(collection) // Output: blog }