我正在 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))
}
海绵宝宝撒
相关分类