3 回答

TA貢獻2051條經驗 獲得超10個贊
如果您想要原始標頭,則需要編寫一些包裝器,以便在庫net.Conn
解釋原始標頭之前為其捕獲原始標頭http
。
但是您似乎并不真的需要原始標頭——甚至根本不需要完整標頭。如果您的目標只是讀取多個 cookie,那么最簡單的方法是使用Cookies
響應中的方法。
這兩者之間的一個中間選項是讀取Header
響應的整個字段。這將顯示完整的標頭,但不能保證其順序,并且將進行最少的解析(刪除換行符等),因此不能說這是真正的“原始”。但是,它確實通過將所有標頭值存儲在一個[]string
.?因此,就這個問題而言,這應該是完全足夠的(盡管Response.Cookies
如上所述,會更容易)。

TA貢獻1843條經驗 獲得超7個贊
在我看來,往返響應的最佳選擇是 httputil#DumpResponse:
package raw
import (
"bufio"
"bytes"
"net/http"
"net/http/httputil"
)
func encode(res *http.Response) ([]byte, error) {
return httputil.DumpResponse(res, false)
}
func decode(data []byte) (*http.Response, error) {
return http.ReadResponse(bufio.NewReader(bytes.NewReader(data)), nil)
}
或者,如果您只想要 cookie,您可以這樣做:
package raw
import (
"encoding/json"
"net/http"
)
func encode(res *http.Response) ([]byte, error) {
return json.Marshal(res.Cookies())
}
func decode(data []byte) ([]http.Cookie, error) {
var c []http.Cookie
if e := json.Unmarshal(data, &c); e != nil {
return nil, e
}
return c, nil
}
或者對于單個 cookie:
package raw
import (
"encoding/json"
"net/http"
)
func encode(res *http.Response, name string) ([]byte, error) {
for _, c := range res.Cookies() {
if c.Name == name {
return json.Marshal(c)
}
}
return nil, http.ErrNoCookie
}
func decode(data []byte) (*http.Cookie, error) {
c := new(http.Cookie)
if e := json.Unmarshal(data, c); e != nil {
return nil, e
}
return c, nil
}
https://golang.org/pkg/net/http/httputil#DumpResponse
- 3 回答
- 0 關注
- 245 瀏覽
添加回答
舉報