猿问

在 Go 中读取 cookie

我正在 Go 中部署一个简单的 HTTP 服务器和一个简单的 HTTP 客户端。我试图从客户端读取 cookie 值但没有成功(我收到一个空值),即使在服务器上设置了我看到的值。我如何从客户端读取 cookie 值(即通过包含我收到的 cookie 来发送进一步的请求)?


服务器代码


package main


import (

    "log"

    "math/rand"

    "net/http"

    "strconv"

    "strings"

    "time"

)


var SERVER_PORT string = ":8080"


func setCookie(w http.ResponseWriter, username string){

    cookieValue := username + ":" + (username+strconv.Itoa(rand.Intn(100000000)))

    //expiration := time.Now().Add(365 * 24 * time.Hour)

    expiration := time.Now().Add(20 * time.Second)

    cookie := http.Cookie{Name:"SessionID", Value: cookieValue, Expires: expiration}

    http.SetCookie(w, &cookie)

    log.Print(cookie)

}


func sayHello(w http.ResponseWriter, r* http.Request) {

    username := r.URL.Path

    username = strings.TrimPrefix(username, "/")

    setCookie(w,username)

    message := "Hello " + username

    w.Write([]byte(message))

}


func ReadCookieServer(w http.ResponseWriter, req *http.Request) {

    // read cookie

    var cookie,err = req.Cookie("SessionID")

    if err == nil {

        var cookievalue = cookie.Value

        w.Write([]byte(cookievalue))

    }

}


func main() {

    http.HandleFunc("/", sayHello)

    http.HandleFunc("/readcookie", ReadCookieServer)

    if err := http.ListenAndServe(SERVER_PORT, nil); err != nil {

        panic(err)

    }

}

客户代码


package main


import (

    "io/ioutil"

    "log"

    http "net/http"

)


var serverName string = "http://localhost"

var serverPort string = ":8080/"


func MakeRequest() {

    var username string = "blabla"

    resp, err := http.Get(serverName + serverPort + username)

    if err != nil {

        log.Fatalln(err)

    }

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {

        log.Fatalln(err)

    }

    log.Println(string(body))

}




PIPIONE
浏览 125回答 1
1回答

海绵宝宝撒

如果你想从 HTTP 请求中读取 cookie,你可以使用Cookies方法来完成。例子:func Readcookie() {    resp, err := http.Get(serverName + serverPort + "readcookie")    if err != nil {        log.Fatalln(err)    }    for _, cookie := range resp.Cookies() {        if cookie.Name == "SessionID" {            log.Println("Cookie: ", cookie.Value)        }    }    body, err := ioutil.ReadAll(resp.Body)    if err != nil {        log.Fatalln(err)    }    log.Println(string(body))}为了实现跨后续 HTTP 请求的会话管理的更大目标,只需在 HTTP 客户端上实例化一个 cookie jar。例子:var client *http.Clientfunc init() {    jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})    if err != nil {        panic(err)    }    client = &http.Client{Jar: jar}}然后为您的后续请求使用此客户端(而不是默认客户端):func Readcookie() {    resp, err := client.Get(serverName + serverPort + "readcookie")    if err != nil {        log.Fatalln(err)    }    body, err := ioutil.ReadAll(resp.Body)    if err != nil {        log.Fatalln(err)    }    log.Println(string(body))}   
随时随地看视频慕课网APP

相关分类

Go
我要回答