英文:
Parse cookie string in golang
问题
如果我在浏览器中通过输入 document.cookie
来获取 cookie,是否有办法解析原始字符串并将其保存为 http.Cookie?
英文:
If I get the cookie by typing document.cookie
in the browser, is there any way to parse the raw string and save it as a http.Cookie?
答案1
得分: 35
稍微简化的版本
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]
}
http://play.golang.org/p/PLVwT6Kzr9
英文:
A bit shorter version
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]
}
答案2
得分: 14
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 (
"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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论