douyun6399 2018-10-27 14:02
浏览 65
已采纳

在Go中读取Cookie

I'm deploying a simple HTTP server and a simple HTTP client in Go. I tried to read the cookie value from the client without success (I receive an empty value) even if on the server the value that I see is set. How can I read the cookie value from the client side (i.e. to send the further requests by including the cookie that I received)?

Server Code

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

Client Code

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()
}
  • 写回答

1条回答 默认 最新

  • douxing2156 2018-10-27 14:43
    关注

    If you want to read the cookie from an HTTP request, you do it with the Cookies method. Example:

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

    To achieve your larger goal, of session management across subsequent HTTP requests, simply instantiate a cookie jar on your HTTP client. Example:

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

    Then use this client (rather than the default) for your subsequent requests:

    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))
    }   
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员