mysql

package module
v3.0.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2018 License: MIT Imports: 9 Imported by: 24

README

MySQL store for Session

Build Codecov ReportCard GoDoc License

Quick Start

Download and install
$ go get -u -v github.com/go-session/mysql
Create file server.go
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/go-session/mysql"
	"github.com/go-session/session"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/myapp_test?charset=utf8"
	session.InitManager(
		session.SetStore(mysql.NewStore(mysql.NewConfig(dsn), "", 0)),
	)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		store, err := session.Start(context.Background(), w, r)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		store.Set("foo", "bar")
		err = store.Save()
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		http.Redirect(w, r, "/foo", 302)
	})

	http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
		store, err := session.Start(context.Background(), w, r)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		foo, ok := store.Get("foo")
		if ok {
			fmt.Fprintf(w, "foo:%s", foo)
			return
		}
		fmt.Fprint(w, "does not exist")
	})

	http.ListenAndServe(":8080", nil)
}

Build and run
$ go build server.go
$ ./server
Open in your web browser

http://localhost:8080

foo:bar

MIT License

Copyright (c) 2018 Lyric

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewStore

func NewStore(config *Config, tableName string, gcInterval int) session.ManagerStore

NewStore Create an instance of a mysql store, tableName Specify the stored table name (default go_session), gcInterval Time interval for executing GC (in seconds, default 600)

func NewStoreWithDB

func NewStoreWithDB(db *sql.DB, tableName string, gcInterval int) session.ManagerStore

NewStoreWithDB Create an instance of a mysql store, tableName Specify the stored table name (default go_session), gcInterval Time interval for executing GC (in seconds, default 600)

Types

type Config

type Config struct {
	DSN             string
	ConnMaxLifetime time.Duration
	MaxOpenConns    int
	MaxIdleConns    int
}

Config mysql configuration

func NewConfig

func NewConfig(dsn string) *Config

NewConfig create mysql configuration instance

type SessionItem

type SessionItem struct {
	ID        string
	Value     string
	ExpiredAt int64
}

SessionItem Data items stored in mysql

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL