Search code examples
web-applicationsgoglobal-variablessession-cookiesbeego

Go Namespace/Scope Issue for Global Session Management Across Multiple Packages


First let me say I'm new to Golang. Working with it for a couple of weeks now. Really like the language but...

I'm having some trouble with global session management in Golang. I see how it works and I can me it work if scope is all in one package, however I just recently created new packages for each of my go files. I did this because I read this is best practice and good for reusability.

Ever since I moved the go files into their own packages instead of one package, the session management broke. It looks to create a new session every time instead of reusing an existing session. Here's some code to give you an understanding of what I'm doing:

package main

import (
    "net/http"
    "api/login"
    "api/globalsessionkeeper"
    "github.com/astaxie/beego/session"
)

func main() {
    http.HandleFunc("/login", login.DoLogin)

    og.Fatal(http.ListenAndServe(":8000", nil))
}

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func init() {
    var err error
    fmt.Println("Session init")
    globalsessionkeeper.GlobalSessions, err = session.NewManager("mysql", `{"enableSetCookie":true, "SessionOn":true, "cookieName":"globalsession_id","gclifetime":120,"ProviderConfig":"root@tcp(172.16.0.23:3306)/databse"}`)
    if err != nil {
        fmt.Printf("Error")
    }
    globalsessionkeeper.GlobalSessions.SetSecure(true)
    go globalsessionkeeper.GlobalSessions.GC()
}

package globalsessionkeeper (I created this just so I can reuse a global variable within all other packages..i.e "package login"..etc)

package globalsessionkeeper

import (
    "github.com/astaxie/beego/session"
    _ "github.com/astaxie/beego/session/mysql"
)

//Global Variable
var GlobalSessions *session.Manager

Here's a snipit from the login function/package. This was working perfectly fine with everything was in one package:

if validated == true {
    //create session using the request data which includes the cookie/sessionid
    sessionStore, err := globalsessionkeeper.GlobalSessions.SessionStart(w, r)
    if err != nil {
        //need logging here instead of print
        fmt.Printf("Error, could not start session %v\n", err)
        break
    }
    defer sessionStore.SessionRelease(w) //update db upon completion for request

    if sessionStore.Get("uniquevalue") == nil {
        //need logging here instead of print
        fmt.Printf("uniquevalue not found, Saving Session, Get has %v\n", sessionStore)
        fmt.Printf("uniquevalue not found, Saving Session, Get has %v\n", sessionStore.Get("uniquevalue"))
        err = sessionStore.Set("uniquevalue", input.uniquevalue)
        if err != nil {
            //need logging here instead of print
            fmt.Printf("Error while writing to DB, %v\n", err)
            break
        }
    } else {
        //need logging here instead of print
        fmt.Printf("Found Session! Session uniquevalue = %v\n", sessionStore.Get("uniquevalue"))
    }
    //Send back 204 no content (with cookie)
    w.WriteHeader(http.StatusNoContent)
} else {
    fmt.Printf("Login Failed")
    w.WriteHeader(http.StatusUnauthorized)
}

The database has the correctly entry. It has the unique value stored for each session that it creates. Here's some output as well:

answer = true
uniquvalue not found, Saving Session, Get has &{0xc208046b80 f08u0489804984988494994 {{0 0} 0 0 0 0} map[]}
uniquevalue not found, Saving Session, Get has <nil>
2015/06/06 17:32:26 http: multiple response.WriteHeader calls

And of course, the multiple response.WriteHeader is something else I have to correct. The go routine was originally sending a 200OK but I wanted to change that to a 204 no content, however it started giving me that error once I did.

Any help would be appreciated. Thanks!


Solution

  • Turns out this was working all along. I was passing the wrong cookie value back to the api. Silly mistakes cause all kinds of headaches.