英文:
Testing request with cookie
问题
我写了一个获取和设置 cookie 的函数。现在我想要对它进行测试,并编写了以下测试函数。
func TestAuthorizationReader(t *testing.T) {
tw := httptest.NewServer(testWriter())
tr := httptest.NewServer(Use(testReader()))
defer tw.Close()
defer tr.Close()
c := &http.Client{}
rs, err := c.Get(tw.URL)
assert.NoError(t, err, "不应该包含任何错误")
// 将 cookie 分配给客户端
url, err := rs.Location()
fmt.Print(url)
assert.NoError(t, err, "不应该包含任何错误")
//c.Jar.SetCookies(url, rs.Cookies())
}
测试在第二部分失败,作为输出信息,我得到了以下内容:
- FAIL: TestAuthorizationReader (0.05s)
Location: logged_test.go:64
Error: 不应该有错误,但是得到了 http: 响应中没有 Location 头部字段
Messages: 不应该包含任何错误
我无法获取 URL 的位置指针,在这里我做错了什么?
英文:
I wrote a cookie getter and setter. Now I want to test it, and wrote following test function.
func TestAuthorizationReader(t *testing.T) {
tw := httptest.NewServer(testWriter())
tr := httptest.NewServer(Use(testReader()))
defer tw.Close()
defer tr.Close()
c := &http.Client{}
rs, err := c.Get(tw.URL)
assert.NoError(t, err, "Should not contain any error")
// Assign cookie to client
url, err := rs.Location()
fmt.Print(url)
assert.NoError(t, err, "Should not contain any error")
//c.Jar.SetCookies(url, rs.Cookies())
}
The test fail at the second part, as output message I've got
- FAIL: TestAuthorizationReader (0.05s)
Location: logged_test.go:64
Error: No error is expected but got http: no Location header in response
Messages: Should not contain any error
I can not get the URL location pointer, what do I wrong here?
答案1
得分: 2
Response.Location
方法返回Location
响应头的值。通常只有在重定向响应中才会看到这个头部,所以你得到这个错误并不奇怪。
如果你想知道用于检索特定响应的URL,请尝试使用rs.Request.URL.String()
。即使HTTP库在检索文档时遵循了重定向,这个方法也会查看用于此特定响应的请求,这是确定cookie来源时需要的。
如果你只想让客户端跟踪处理的请求设置的cookie,你只需要在客户端上设置Jar
属性。像这样:
import "net/http/cookiejar"
...
c := &http.Client{
Jar: cookiejar.New(nil),
}
现在,之前响应中设置的cookie应该会在将来对同一来源的请求中设置。
英文:
The Response.Location
method returns the value of the Location
response header. You would usually only expect to see this header for redirect responses, so it isn't surprising you got this error.
If you want to know the URL used to retrieve a particular response, try rs.Request.URL.String()
. Even if the HTTP library followed a redirect to retrieve the document, this will look at the request used for this particular response, which is what you'd be after when determining a cookie's origin.
If you just want the client to keep track of cookies set by requests it processes though, all you should need to do is set the Jar
attribute on your client. Something like this:
import "net/http/cookiejar"
...
c := &http.Client{
Jar: cookiejar.New(nil),
}
Now cookies set in earlier responses should be set in future requests to the same origin.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论