我正在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()
}
答案 0 :(得分:0)
如果您想从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罐即可。示例:
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))
}