我试图测试一个从Go中的请求中检索Cookie的函数,但即使它们具有相同的值,比较失败。测试从函数返回的Cookie
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"reflect"
)
func GetCookie(url string) *http.Cookie {
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := http.DefaultClient
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
cookies := res.Cookies()
var mycookie *http.Cookie
for _, c := range cookies {
if c.Name == "mycookie" {
mycookie = c
}
}
return mycookie
}
func main() {
validCookie := &http.Cookie{
Name: "mycookie",
Value: "SomeValue",
Path: "/mysite",
HttpOnly: true,
Secure: true,
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, validCookie)
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(200)
}))
defer ts.Close()
fmt.Printf("EqualL Cookies: %t\n", reflect.DeepEqual(validCookie, validCookie))
if got := GetCookie(ts.URL); !reflect.DeepEqual(got, validCookie) {
log.Fatalf("NOT THE SAME\n got = '%v'\nwant = '%v'", got, validCookie)
}
}
游乐场链接:https://play.golang.org/p/T4dbZycMuT
我已经检查了DeepEqual函数的文档,从我能看到2个结构/指针应该是相同的(特别是考虑到cookie没有不导出字段)。
我可以更改函数来比较Cookie字符串,但是我想知道是否有简单的解释为什么这不起作用或者是由于文档指定的“不一致性”。 也有任何方法来测试结构,而不是在这个情况下的字符串表示(或者我犯了一个错误,也许)?