Parse cookie string in golang

huangapple go评论92阅读模式
英文:

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

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

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

Playground

英文:
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

huangapple
  • 本文由 发表于 2015年2月1日 19:52:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/28262376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定