Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse cookie string in golang

Tags:

cookies

go

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?

like image 744
waitingkuo Avatar asked Feb 01 '15 11:02

waitingkuo


2 Answers

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

like image 166
ahmy Avatar answered Sep 21 '22 22:09

ahmy


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

like image 41
Sundrique Avatar answered Sep 22 '22 22:09

Sundrique