dqhgjay5753
dqhgjay5753
2015-02-01 11:52
浏览 442
已采纳

在Golang中解析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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanrong5927
    duanrong5927 2015-02-01 12:43
    已采纳
    package main
    
    import (
        "bufio"
        "fmt"
        "net/http"
        "strings"
    )
    
    func main() {
        rawCookies := "cookie1=value1;cookie2=value2"
        rawRequest := fmt.Sprintf("GET / HTTP/1.0
    Cookie: %s
    
    ", rawCookies)
    
        req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(rawRequest)))
    
        if err == nil {
            cookies := req.Cookies()
            fmt.Println(cookies)
        }
    }
    

    Playground

    点赞 评论
  • drh47606
    drh47606 2015-11-25 20:42

    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]
    }
    

    http://play.golang.org/p/PLVwT6Kzr9

    点赞 评论

相关推荐