Git Product home page Git Product logo

mysqlstore's Introduction

mysqlstore

Gorilla's Session Store Implementation for MySQL

Installation

Run go get github.com/srinathgs/mysqlstore from command line. Gets installed in $GOPATH

Usage

NewMysqlStore takes the following paramaters

endpoint - A sql.Open style endpoint
tableName - table where sessions are to be saved. Required fields are created automatically if the table doesnot exist.
path - path for Set-Cookie header
maxAge 
codecs

Internally, mysqlstore uses this MySQL driver.

e.g.,

  package main

  import (
    "fmt"
    "github.com/srinathgs/mysqlstore"
    "net/http"
  )

  var store *mysqlstore.MySQLStore

  func sessTest(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "foobar")
    session.Values["bar"] = "baz"
    session.Values["baz"] = "foo"
    err = session.Save(r, w)
    fmt.Printf("%#v\n", session)
    fmt.Println(err)
  }

func main() {
    var err error
    store, err = mysqlstore.NewMySQLStore("UN:PASS@tcp(<IP>:<PORT>)/<DB>?parseTime=true&loc=Local", <tablename>, "/", 3600, []byte("<SecretKey>"))
    if err != nil {
      panic(err)
    }
    defer store.Close()

	http.HandleFunc("/", sessTest)
	http.ListenAndServe(":8080", nil)
}

mysqlstore's People

Contributors

dieselburner avatar fiatflux avatar gavbaa avatar irfanhabib avatar jnnewton avatar okostadinov avatar srinathgs avatar swsnider avatar urlund avatar zekrotja avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mysqlstore's Issues

Loading Session Panic.

Hiya,

Loading a session causes the code to panic.

2020/04/13 23:35:47 http: panic serving 127.0.0.1:64951: interface conversion: driver.Value is time.Time, not []uint8 goroutine 103 [running]: net/http.(*conn).serve.func1(0xc0001c2a00) /usr/local/Cellar/go/1.13.7/libexec/src/net/http/server.go:1767 +0x139 panic(0x1410420, 0xc000117170) /usr/local/Cellar/go/1.13.7/libexec/src/runtime/panic.go:679 +0x1b2 github.com/srinathgs/mysqlstore.(*MySQLStore).load(0xc0003c2660, 0xc0003f4500, 0xc000412367, 0x48) /Users/ackers/go/src/github.com/srinathgs/mysqlstore/mysqlstore.go:284 +0xa05 github.com/srinathgs/mysqlstore.(*MySQLStore).New(0xc0003c2660, 0xc000428b00, 0x1485e8a, 0x6, 0x1804460, 0xc0003ce400, 0x6)

MySQL is version 8 running locally on my Mac.

I fixed by changing to this..

//sess.createdOn, _ = time.Parse(timeFormat, string(timeCreated.([]uint8)))
//sess.modifiedOn, _ = time.Parse(timeFormat, string(timeModified.([]uint8)))
//sess.expiresOn, _ = time.Parse(timeFormat, string(timeExpires.([]uint8)))

sess.createdOn = timeCreated.(time.Time)
sess.modifiedOn = timeModified.(time.Time)
sess.expiresOn = timeExpires.(time.Time)

Thanks.

Cannot create table

Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

Any idea?

noob question

Hey guys,

How do I access the store in routes after the middleware. Here is my session middleware func that gets called before any route.

func Init() *mysqlstore.MySQLStore {
	DB_HOST = os.Getenv("DB_HOST")
	DB_PORT = os.Getenv("DB_PORT")
	DB_DATABASE = os.Getenv("DB_DATABASE")
	DB_USER = os.Getenv("DB_USER")
	DB_PASSWORD = os.Getenv("DB_PASSWORD")

	maxAge := 3600
	tableName := "go_sessions"

	connectStr := DB_USER + ":" + DB_PASSWORD + "@tcp(" + DB_HOST + ":" + DB_PORT + ")/" + DB_DATABASE + "?parseTime=true&loc=Local"
	store, err := mysqlstore.NewMySQLStore(connectStr, tableName, "/", maxAge, []byte(os.Getenv("SECRET")))
	if err != nil {
		panic(err)
	}

	return store
}

func Middleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		session, err := store.Get(r, "session")
		if err != nil {
			// TODO: Handle this gracefully...
			panic(err)
		}

		userId := session.Values["userId"]
		log.Println(userId)

		h.ServeHTTP(w, r)
	})
}

Then on a route after the middleware how do I access the session?

package Router

import (
	"../session"
)

var routes = Routes{
	Route{"SessionStore", "POST", "/session/store", Session.Store},
}
package Session

...

// TODO: Create some route that does something with session to test it 

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

    // TODO: Do something with session.Get("TEST")

}

add go module

add go module. it won't hurt anybody (or so I thought).

Cross Web Server Session

I want to use multiple servers to serve one website. If the user login in one server, I expect he also login in other server and have right to access his own session data. Is srinathgs/mysqlstore a good choice and stable enough for doing this? When the MySQL server is shut down, will all session data get destroyed?

Actually, I have 12 ubuntu servers under the same domain. Some of them will be used as web servers and one will be used as a MySQL database server. Therefore, I want to implement a MySQL-based session service to allow session data synchronized in all web servers.

MySQLStore.New() sets only Path & MaxAge session options

Currently new sessions does not honor all of the options that was set to Store.

That is, following options are currently ignored:

store := MySQLStore(...)
store.Options(Options{
    Domain:   "fbi.gov",
    Secure:   false,
    HttpOnly: true,
})

Because of:

func (m *MySQLStore) New(r *http.Request, name string) (*sessions.Session, error) {
    session := sessions.NewSession(m, name)
    session.Options = &sessions.Options{
        Path:   m.Options.Path,
        MaxAge: m.Options.MaxAge,
    }

Entire Options structure should be copied, instead of just two fields, Path and MaxAge.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.