3 回答

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

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
在我看來(lái),往返響應(yīng)的最佳選擇是 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
}
或者對(duì)于單個(gè) 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

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
標(biāo)準(zhǔn)的 http 庫(kù)默認(rèn)解析標(biāo)頭。
使用 fasthttp(您需要重新編寫路由器和處理程序函數(shù))將使您能夠獲取原始標(biāo)頭。
- 3 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報(bào)