想要在客户端发送新请求时获取会话值

时间:2017-07-03 08:55:31

标签: session go gorilla

我想在客户端创建新请求时获取服务器的会话值。

但是,服务器总是返回nil。

在这种情况下,我不知道问题是什么。

客户端

package main

import (
    "io/ioutil"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var (
    store       *sessions.CookieStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
    session     *sessions.Session
    SessionName = "client"
)

func main() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   60 * 15,
        Secure:   false,
        HttpOnly: true,
    }
    router := mux.NewRouter()
    router.HandleFunc("/", cIndex)
    router.HandleFunc("/test", cTest)
    http.ListenAndServe(":7000", router)
}

func cIndex(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("cIndex Session Error : ", err.Error())
        return
    }
    session.Values["foo"] = "bar"
    session.Save(r, w)
    w.Header().Set("Location", "http://localhost:8080?foo=bar")
    w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
    w.WriteHeader(http.StatusFound)

}

func cTest(w http.ResponseWriter, r *http.Request) {
    req, err := http.NewRequest("GET", "http://localhost:8080/test", nil)
    if err != nil {
        log.Println("cTest Request Error : ", err.Error())
        return
    }
    req.SetBasicAuth("sample_id", "sample_secret")
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    c := &http.Client{
        Transport: &http.Transport{},
    }
    resp, err := c.Do(req)
    if err != nil {
        log.Println("cTest Response Error : ", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("cTest Body Error : ", err.Error())
        return
    }
    log.Println(string(body))
}

服务器

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var (
    store       *sessions.CookieStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
    session     *sessions.Session
    SessionName = "server"
)

func main() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   60 * 15,
        Secure:   false,
        HttpOnly: true,
    }
    router := mux.NewRouter()
    router.HandleFunc("/", sIndex)
    router.HandleFunc("/test", sTest)
    http.ListenAndServe(":8080", router)
}

func sIndex(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    v := r.FormValue("foo")
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("sIndex Session Error : ", err.Error())
        return
    }
    session.Values["foo"] = v
    session.Save(r, w)
    w.Header().Set("Location", "http://localhost:7000/test")
    w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
    w.WriteHeader(http.StatusFound)
}

func sTest(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("sTest Session Error : ", err.Error())
        return
    }
    v, ok := session.Values["foo"].(string)
    if !ok {
        log.Printf("foo = %v\n", v)
    }
    data := struct {
        Foo string
    }{
        v, // I expected v is bar,but v was nil.
    }

    bytes, err := json.Marshal(data)
    if err != nil {
        log.Println("sTest JSON Error : ", err.Error())
        return
    }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(bytes)
}

详细

  1. 客户端向查询foo=bar的服务器发送请求。

  2. 服务器接收请求并解析。

  3. 服务器在会话中保存查询参数。(我使用gorilla/session

  4. 客户端生成*http.Client并向服务器发送新请求。

  5. 服务器接收请求,并在会话中加载值,并在响应时设置值。

  6. 客户收到价值bar

  7. 在5中,我希望服务器可以从会话加载值bar,但会话值为零。

1 个答案:

答案 0 :(得分:0)

我写了一些代码然后移动了。 这是正确的方法吗?

客户端

func cTest(w http.ResponseWrite, r *http.Request) {
    serverURL := "http://localhost:8080/test"
    r.Method = http.MethodGet
    r.Host = serverURL  // server
    v, err := url.Parse(serverURL)
    if err != nil {
        log.Println("url parsing error occurred : ", err.Error())
        return
    }
    c := &http.Client{Transport: &http.Transport{}}
    resp, err := c.Transport.RoundTrip(r)
    if err != nil {
        log.Println("client roundtrip error occurred : ", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("response body reading error occurred : ", err.Error())
        return
    }
    w.Write(body)
}