在Go中读取cookie

ezykj2lf  于 11个月前  发布在  Go
关注(0)|答案(2)|浏览(86)

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

func Readcookie() {
    resp, err := http.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))
}

func main() {
    MakeRequest()
    Readcookie()
}

nwo49xxi

nwo49xxi1#

如果你想从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.Client

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

ssgvzors

ssgvzors2#

首先,检查客户端是否正在保存cookie。检查浏览器>存储> Cookie。如果客户端正在获取cookie,请记住在客户端请求凭据时启用。

fetch("http://example.com/data.json", {
       credentials: "include"
})

字符串
查看更多:https://sabe.io/blog/javascript-pass-cookies-fetch-axios

相关问题