update
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
package httpc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
HeaderUserAgent = "User-Agent"
|
||||
HeaderContentType = "Content-Type"
|
||||
@@ -17,3 +23,66 @@ const (
|
||||
AcceptHtml = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
|
||||
AcceptCNLanguage = "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
|
||||
)
|
||||
|
||||
func RedirectAllCookies(req *http.Request, via []*http.Request) error {
|
||||
_, cookieHeader := GetRedirectCookieHeaders(req, via)
|
||||
if cookieHeader != "" {
|
||||
req.Header.Set("Cookie", cookieHeader)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetRedirectCookieHeaders(req *http.Request, via []*http.Request) (map[string]string, string) {
|
||||
if len(via) == 0 {
|
||||
return map[string]string{}, ""
|
||||
}
|
||||
|
||||
lastReq := via[len(via)-1]
|
||||
|
||||
cookieMap := parseCookieMap(lastReq.Header.Get("Cookie"))
|
||||
|
||||
for _, c := range lastReq.Cookies() {
|
||||
cookieMap[c.Name] = c.Value
|
||||
}
|
||||
|
||||
if lastReq.Response != nil {
|
||||
for _, c := range lastReq.Response.Cookies() {
|
||||
cookieMap[c.Name] = c.Value
|
||||
}
|
||||
}
|
||||
|
||||
var pairs []string
|
||||
for name, value := range cookieMap {
|
||||
pairs = append(pairs, fmt.Sprintf("%s=%s", name, value))
|
||||
}
|
||||
|
||||
if len(pairs) > 0 {
|
||||
// 直接 Set 最终合并后的完整字符串
|
||||
return cookieMap, strings.Join(pairs, "; ")
|
||||
}
|
||||
|
||||
return map[string]string{}, ""
|
||||
}
|
||||
|
||||
func parseCookieMap(str string) map[string]string {
|
||||
res := make(map[string]string)
|
||||
if len(str) == 0 {
|
||||
return res
|
||||
}
|
||||
|
||||
sp := strings.Split(str, ";")
|
||||
|
||||
for _, v := range sp {
|
||||
split := strings.SplitN(v, "=", 2)
|
||||
if len(split) == 2 {
|
||||
name := strings.TrimSpace(split[0])
|
||||
value := strings.TrimSpace(split[1])
|
||||
|
||||
if name != "" && value != "" {
|
||||
res[name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user