我正在尝试测试一个从 Go 中的请求中检索 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 字符串,但是我想知道是否有一个简单的解释为什么这不起作用或者是由于文档指定的“不一致”。还有什么方法可以在这个场景中测试结构而不是字符串表示(或者我可能犯了错误)?