在golang中解析cookie字符串

时间:2015-02-01 11:52:35

标签: cookies go

如果我在浏览器中输入document.cookie来获取cookie,有没有办法解析原始字符串并将其另存为http.Cookie

2 个答案:

答案 0 :(得分:15)

稍短的版本

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

答案 1 :(得分:10)

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

Playground