大猩猩会议不会持续在Golang中

I'm having trouble with persisting the sessions in Golang using the Gorilla session handler. Similar issues (unresolved!) have been brought up in other stack overflow questions (here: Sessions variables in golang not saved while using gorilla sessions and here: cannot get gorilla session value by key). This is very scary, as it seems that 1) it is not just me 2) there does not seem to be a solution that currently exists 3) the Gorilla Sessions package may be fundamentally broken.

Here is the problem in more detail:

I can set sessions no problem when logging in. However, after I am logged in and I make another request to the backend the sessions values are not persisted, meaning that I cannot pull sessions.Value['username'] for example (even though that is the point of sessions).

So:

A) Log in, write sessions, retrieve session.Value['usernames'] and it works fine.

B) Navigate to another page on the front end and make another request to the backend (make a new character).

C) Attempt to retrieve session.Value['username']. It's nil!!!!

Here is the flow the user navigates on the backend to log in -

First here is the session handler:

package config

import (
    "log"
    "net/http"

    "github.com/gorilla/sessions"
)

type Options struct {
    Path     string
    Domain   string
    MaxAge   int
    Secure   bool
    HttpOnly bool
}

type Session struct {
    ID      string
    Values  map[interface{}]interface{}
    Options *Options
    IsNew   bool
}

type Store interface {
    Get(r *http.Request, name string) (*sessions.Session, error)
    New(r *http.Request, name string) (*sessions.Session, error)
    Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
}

var SessionsStore = sessions.NewCookieStore([]byte("secret"))

func init() {
    SessionsStore.Options = &sessions.Options{
        Domain:   "localhost",
        Path:     "/",
        MaxAge:   3600 * 8, // 8 hours
        HttpOnly: true,
    }
}

func KeyStore() (store Store) {

    log.Print("inside KeyStore")
    store = SessionsStore
    log.Print("Value of store is : ", store)
    return store
}

Next, here is how I get from main to the routing to each of my components:

Main

package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"
    "os"

    _ "github.com/lib/pq"
    "github.com/patientplatypus/gorest/config"

    "github.com/gorilla/handlers"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "patientplatypus"
    password = "superdupersecretyo"
    dbname   = "dungeon_world"
)

func main() {

    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        "localhost", 5432, "patientplatypus", "supersecret", "dungeon_world")
    var err error
    config.DB, err = sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }

    err = config.DB.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected~!")

    router := NewRouter()
    os.Setenv("ORIGIN_ALLOWED", "*")
    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
    originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

    log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, methodsOk)(router)))

}

Here is the routing package that routes to each handler:

package main

import (
    "net/http"

    "github.com/patientplatypus/gorest/users"

    "github.com/patientplatypus/gorest/dungeon_db"

    "github.com/patientplatypus/gorest/character"

    "github.com/patientplatypus/gorest/createcharacter"

    "github.com/gorilla/mux"
)

type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

func NewRouter() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(route.HandlerFunc)
    }

    return router
}

var routes = Routes{
    Route{
        "ClassType",
        "POST",
        "/character/class",
        character.ClassType,
    },
    <MORE ROUTES FOLLOWING SAME PATTERN>
}

Now here is the login function. This is where I wrote the original session and printed out session.Values['username'] to show that it works:

package users

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

    "github.com/patientplatypus/gorest/config"
)

type LoginResponse struct {
    Status string
}

type User struct {
    Username string
    Password string
    Id       int
}

func UserLogin(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)

    var incomingjson User
    err := decoder.Decode(&incomingjson)

    if err != nil {
        panic(err)
    }

    username := incomingjson.Username
    password := incomingjson.Password

    log.Print("username: ", username)
    log.Print("password: ", password)
    if username != "" && password != "" {
        incomingjson.Login(w, r)
    } else {
        fmt.Fprintln(w, "error username or password is blank!")
    }
}

func (incomingjson *User) Login(w http.ResponseWriter, r *http.Request) {
    session, _ := config.KeyStore().Get(r, "cookie-name")
    log.Print("loginjson: ", incomingjson)
    var tempvar string

    err := config.DB.QueryRow("SELECT username FROM users WHERE username=$1;", incomingjson.Username).Scan(&tempvar)
    log.Print("err: ", err)
    if err == nil {
        // 1 row
        log.Print("Found username")
        var passwordindatabase string
        config.DB.QueryRow("SELECT password FROM users WHERE username=$1;", &incomingjson.Username).Scan(&passwordindatabase)
        if passwordindatabase == incomingjson.Password {
            log.Print("username and password match!")
            session.Values["authenticated"] = true
            session.Values["username"] = incomingjson.Username
            config.KeyStore().Save(r, w, session)
            response := LoginResponse{Status: "Success, user logged in"}
            json.NewEncoder(w).Encode(response)
        } else {
            log.Print("username and password don't match!")
            session.Values["authenticated"] = false
            session.Values["username"] = ""
            config.KeyStore().Save(r, w, session)
            response := LoginResponse{Status: "Failure, username and password don't match"}
            json.NewEncoder(w).Encode(response)
        }
    } else {
        //empty result or error
        log.Print("Username not found or there was an error: ", err)
        response := LoginResponse{Status: "User not found!"}
        json.NewEncoder(w).Encode(response)
    }
}

Now here is the problem component. It's job is to make a new character after checking that the user exists (sessioncheck is ok)...

So here I have:

package createcharacter

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

    "github.com/patientplatypus/gorest/config"
)

var Username string
var Checkok bool


func SessionsCheck(w http.ResponseWriter, r *http.Request) (username string, checkok bool) {
    store := config.KeyStore()
    session, _ := store.Get(r, "cookie-name")
    log.Print("inside sessionscheck...what is the value of stuff....")
    log.Print("session: ", session)
    log.Print("session.Values: ", session.Values)
    log.Print("username: ", session.Values["username"])
    log.Print("authenticated: ", session.Values["authenticated"])
    if session.Values["username"] == nil {
        if session.Values["authenticated"] == false {
            log.Print("Verboten!")
            http.Error(w, "Forbidden", http.StatusForbidden)
            return "nil", false
        }
    }
    return session.Values["username"].(string), true
}

func NewCharacter(w http.ResponseWriter, r *http.Request) {
    Username, Checkok = SessionsCheck(w, r)
    <FUNCTION CONTINUES>

This is where I am getting the error...but I don't know how to fix.

The terminal output is :

2017/10/15 15:08:56 inside KeyStore
2017/10/15 15:08:56 Value of store is : &{[0xc42010c000] 0xc42007d5f0}
2017/10/15 15:08:56 inside sessionscheck...what is the value of stuff....
2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
2017/10/15 15:08:56 session.Values: map[]
2017/10/15 15:08:56 username: <nil>
2017/10/15 15:08:56 authenticated: <nil>
2017/10/15 15:08:56 http: panic serving [::1]:53668: interface conversion: interface {} is nil, not string
goroutine 13 [running]:
net/http.(*conn).serve.func1(0xc42015c5a0)
    /usr/local/opt/go/libexec/src/net/http/server.go:1697 +0xd0
panic(0x133bcc0, 0xc420061f00)
    /usr/local/opt/go/libexec/src/runtime/panic.go:491 +0x283
github.com/patientplatypus/gorest/createcharacter.SessionsCheck(0x1540d00, 0xc42010a540, 0xc42014ea00, 0xc42011ab00, 0x3, 0xc420001680)
    /Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:31 +0x5c9
github.com/patientplatypus/gorest/createcharacter.NewCharacter(0x1540d00, 0xc42010a540, 0xc42014ea00)
    /Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:35 +0x5a
net/http.HandlerFunc.ServeHTTP(0x13b8690, 0x1540d00, 0xc42010a540, 0xc42014ea00)
    /usr/local/opt/go/libexec/src/net/http/server.go:1918 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc420066360, 0x1540d00, 0xc42010a540, 0xc42014ea00)
    /Users/patientplatypus/Documents/golang/src/github.com/gorilla/mux/mux.go:133 +0xed
github.com/gorilla/handlers.(*cors).ServeHTTP(0xc42010c7e0, 0x1540d00, 0xc42010a540, 0xc42014e800)
    /Users/patientplatypus/Documents/golang/src/github.com/gorilla/handlers/cors.go:118 +0x5c8
net/http.serverHandler.ServeHTTP(0xc42014a000, 0x1540d00, 0xc42010a540, 0xc42014e800)
    /usr/local/opt/go/libexec/src/net/http/server.go:2619 +0xb4
net/http.(*conn).serve(0xc42015c5a0, 0x1541240, 0xc420061dc0)
    /usr/local/opt/go/libexec/src/net/http/server.go:1801 +0x71d
created by net/http.(*Server).Serve
    /usr/local/opt/go/libexec/src/net/http/server.go:2720 +0x288

I am sorry for the verbosity, but I think this is the most minimal example I can reproduce from my code base. If anyone has any suggestions please let me know.

EDIT:

One thing that I have noticed is the following:

2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
2017/10/15 15:08:56 session.Values: map[]

Seems to indicate that the username and authenticated (true 0xc4200e0a80) are being stored outside of the session.Values []map function. Why is that?

EDIT EDIT:

So...I thought that the way that I wrote config.KeyStore() may have been an issue so I rewrote it to the following and the persisted it throughout the project:

package config

import (
    "github.com/gorilla/sessions"
)

var SessionsStore = sessions.NewCookieStore([]byte("secret"))

func init() {
    SessionsStore.Options = &sessions.Options{
        Domain:   "localhost",
        Path:     "/",
        MaxAge:   3600 * 8, // 8 hours
        HttpOnly: true,
    }
}

So now wherever I need SessionsStore I just call conf.SessionsStore. That's seemingly as canonical a way to do it as I think is possible. I still have the same issue.

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

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

const appCookie = "myappcookies"

var cookies *sessions.CookieStore

func Login(w http.ResponseWriter, r *http.Request) {
    //
    // For the sake of simplicity, I am using a global here. 
    // You should be using a context.Context instead!
    session, err := cookies.Get(r, appCookie)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        log.Println(err)
        return
    }
    session.Values["userName"] = "StackOverflow"
    session.Save(r, w)
}

func Session(w http.ResponseWriter, r *http.Request) {
    session, err := cookies.Get(r, appCookie)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        log.Println(err)
        return
    }
    w.Write([]byte(fmt.Sprintf("Objects in session: %d
", len(session.Values))))
    for k, v := range session.Values {
        w.Write([]byte(fmt.Sprintf("Key=%v, Value=%v
", k, v)))
    }
}

func main() {
    cookies = sessions.NewCookieStore([]byte("mysuperdupersecret"))
    router := mux.NewRouter()
    router.Path("/login").Methods(http.MethodPost).HandlerFunc(Login)
    router.Path("/session").Methods(http.MethodGet).HandlerFunc(Session)
    server := &http.Server{
        Handler: router,
        Addr:    ":8000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }
    log.Fatal(server.ListenAndServe())
}