Skip to content

Commit b4456df

Browse files
vdoblerbradfitz
authored andcommitted
net/http: add cookies from jar to POST request.
The main content of this CL is a test case checking the reported issue 3511 and a tiny fix for it. A subsequent CL will refactor the fix as proposed issue 3511. Fixes golang#3511. R=golang-dev, steven.hartland, bradfitz CC=golang-dev https://golang.org/cl/6013049
1 parent 30c0d23 commit b4456df

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/pkg/net/http/client.go

+5
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,11 @@ func (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response,
278278
return nil, err
279279
}
280280
req.Header.Set("Content-Type", bodyType)
281+
if c.Jar != nil {
282+
for _, cookie := range c.Jar.Cookies(req.URL) {
283+
req.AddCookie(cookie)
284+
}
285+
}
281286
r, err = send(req, c.Transport)
282287
if err == nil && c.Jar != nil {
283288
c.Jar.SetCookies(req.URL, r.Cookies())

src/pkg/net/http/client_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,31 @@ var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request)
256256
}
257257
})
258258

259+
func TestClientSendsCookieFromJar(t *testing.T) {
260+
tr := &recordingTransport{}
261+
client := &Client{Transport: tr}
262+
client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
263+
us := "http://dummy.faketld/"
264+
u, _ := url.Parse(us)
265+
client.Jar.SetCookies(u, expectedCookies)
266+
267+
client.Get(us) // Note: doesn't hit network
268+
matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
269+
270+
client.Head(us) // Note: doesn't hit network
271+
matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
272+
273+
client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
274+
matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
275+
276+
client.PostForm(us, url.Values{}) // Note: doesn't hit network
277+
matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
278+
279+
req, _ := NewRequest("GET", us, nil)
280+
client.Do(req) // Note: doesn't hit network
281+
matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
282+
}
283+
259284
// Just enough correctness for our redirect tests. Uses the URL.Host as the
260285
// scope of all cookies.
261286
type TestJar struct {

0 commit comments

Comments
 (0)