diff --git a/httpbin/handlers.go b/httpbin/handlers.go index 5f8c8afc413d2a282eb0d018585ceefedcc74322..46a9b647d2cf716cb153597838702c8fab7474ee 100644 --- a/httpbin/handlers.go +++ b/httpbin/handlers.go @@ -254,3 +254,21 @@ func (h *HTTPBin) Cookies(w http.ResponseWriter, r *http.Request) { body, _ := json.Marshal(resp) writeJSON(w, body, http.StatusOK) } + +// SetCookies sets cookies as specified in query params and redirects to +// Cookies endpoint +func (h *HTTPBin) SetCookies(w http.ResponseWriter, r *http.Request) { + params := r.URL.Query() + for k, vs := range params { + for _, v := range vs { + fmt.Printf("setting cookie %#v = %#v\n", k, v) + http.SetCookie(w, &http.Cookie{ + Name: k, + Value: v, + HttpOnly: true, + }) + } + } + w.Header().Set("Location", "/cookies") + w.WriteHeader(http.StatusFound) +} diff --git a/httpbin/handlers_test.go b/httpbin/handlers_test.go index 5cc3be91e3dbf8a344cbd6d3327042e20de72332..883db790fb845b0f2541e8b4183805abc60d89b6 100644 --- a/httpbin/handlers_test.go +++ b/httpbin/handlers_test.go @@ -837,21 +837,53 @@ func TestCookies(t *testing.T) { } } - t.Run("no cookies", func(t *testing.T) { + t.Run("ok/no cookies", func(t *testing.T) { testCookies(t, cookiesResponse{}) }) - t.Run("single cookies", func(t *testing.T) { + t.Run("ok/single cookies", func(t *testing.T) { testCookies(t, cookiesResponse{ "k1": {"v1"}, "k2": {"v2"}, }) }) - t.Run("duplicate cookies", func(t *testing.T) { + t.Run("ok/duplicate cookies", func(t *testing.T) { testCookies(t, cookiesResponse{ "k1": {"v1"}, "k2": {"v2a", "v2b"}, }) }) } + +func TestSetCookies(t *testing.T) { + cookies := cookiesResponse{ + "k1": {"v1"}, + "k2": {"v2a", "v2b"}, + } + + params := url.Values(cookies) + + r, _ := http.NewRequest("GET", fmt.Sprintf("/cookies/set?%s", params.Encode()), nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + + assertStatusCode(t, w, http.StatusFound) + assertHeader(t, w, "Location", "/cookies") + + for _, c := range w.Result().Cookies() { + values, ok := cookies[c.Name] + if !ok { + t.Fatalf("got unexpected cookie %s=%s", c.Name, c.Value) + } + found := false + for _, v := range values { + if v == c.Value { + found = true + } + } + if !found { + t.Fatalf("got cookie %s=%s, expected value in %#v", c.Name, c.Value, values) + } + } +} diff --git a/httpbin/httpbin.go b/httpbin/httpbin.go index 7080e251706b7fd3daa3670b641207ffcbc37a4b..cf06ed40659dcb1a237cac8604cd8eb7ef967296 100644 --- a/httpbin/httpbin.go +++ b/httpbin/httpbin.go @@ -76,6 +76,7 @@ func (h *HTTPBin) Handler() http.Handler { mux.HandleFunc("/absolute-redirect/", h.AbsoluteRedirect) mux.HandleFunc("/cookies", h.Cookies) + mux.HandleFunc("/cookies/set", h.SetCookies) // Make sure our ServeMux doesn't "helpfully" redirect these invalid // endpoints by adding a trailing slash. See the ServeMux docs for more