在golang中解析cookie字符串
Parse cookie string in golang
如果我通过在浏览器中输入 document.cookie
获取 cookie,有什么方法可以解析原始字符串并将其保存为 http.Cookie?
package main
import (
"bufio"
"fmt"
"net/http"
"strings"
)
func main() {
rawCookies := "cookie1=value1;cookie2=value2"
rawRequest := fmt.Sprintf("GET / HTTP/1.0\r\nCookie: %s\r\n\r\n", rawCookies)
req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(rawRequest)))
if err == nil {
cookies := req.Cookies()
fmt.Println(cookies)
}
}
稍微短一点的版本
package main
import (
"fmt"
"net/http"
)
func main() {
rawCookies := "cookie1=value1;cookie2=value2"
header := http.Header{}
header.Add("Cookie", rawCookies)
request := http.Request{Header: header}
fmt.Println(request.Cookies()) // [cookie1=value1 cookie2=value2]
}
如果我通过在浏览器中输入 document.cookie
获取 cookie,有什么方法可以解析原始字符串并将其保存为 http.Cookie?
package main
import (
"bufio"
"fmt"
"net/http"
"strings"
)
func main() {
rawCookies := "cookie1=value1;cookie2=value2"
rawRequest := fmt.Sprintf("GET / HTTP/1.0\r\nCookie: %s\r\n\r\n", rawCookies)
req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(rawRequest)))
if err == nil {
cookies := req.Cookies()
fmt.Println(cookies)
}
}
稍微短一点的版本
package main
import (
"fmt"
"net/http"
)
func main() {
rawCookies := "cookie1=value1;cookie2=value2"
header := http.Header{}
header.Add("Cookie", rawCookies)
request := http.Request{Header: header}
fmt.Println(request.Cookies()) // [cookie1=value1 cookie2=value2]
}