Skip to content
Snippets Groups Projects
Commit d6e94c95 authored by Will McCutchen's avatar Will McCutchen
Browse files

Add /cookies/set handler

parent d0f764cc
No related branches found
No related tags found
No related merge requests found
......@@ -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)
}
......@@ -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)
}
}
}
......@@ -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
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment