waitingkuo
waitingkuo

Reputation: 93984

Parse cookie string in golang

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?

Upvotes: 27

Views: 21234

Answers (3)

jmckenzi
jmckenzi

Reputation: 21

Shorter again! Go 1.23.0 now has a ParseCookie function.

package main

import (
    "net/http"
)

func main() {
    cookieStr := "session_id=abc123; user_id=42"
    cookies, err := http.ParseCookie(cookieStr)
    if err != nil {
        panic(err)
    }

    for _, cookie := range cookies {
        println("Name:", cookie.Name, "Value:", cookie.Value)
    }
}

Upvotes: 2

ahmy
ahmy

Reputation: 4365

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

Upvotes: 39

Sundrique
Sundrique

Reputation: 637

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

Upvotes: 14

Related Questions