|
1 |
| -# mysql |
2 |
| -MySQL store for Session. |
| 1 | +# MySQL store for [Session](https://github.com/go-session/session) |
| 2 | + |
| 3 | +[![ReportCard][reportcard-image]][reportcard-url] [![GoDoc][godoc-image]][godoc-url] [![License][license-image]][license-url] |
| 4 | + |
| 5 | +## Quick Start |
| 6 | + |
| 7 | +### Download and install |
| 8 | + |
| 9 | +```bash |
| 10 | +$ go get -u -v github.com/go-session/mysql |
| 11 | +``` |
| 12 | + |
| 13 | +### Create file `server.go` |
| 14 | + |
| 15 | +```go |
| 16 | +package main |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "fmt" |
| 21 | + "net/http" |
| 22 | + |
| 23 | + "github.com/go-session/mysql" |
| 24 | + "github.com/go-session/session" |
| 25 | + _ "github.com/go-sql-driver/mysql" |
| 26 | +) |
| 27 | + |
| 28 | +func main() { |
| 29 | + dsn := "root:123456@tcp(127.0.0.1:3306)/myapp_test?charset=utf8" |
| 30 | + session.InitManager( |
| 31 | + session.SetStore(mysql.NewStore(mysql.NewConfig(dsn), "", 0)), |
| 32 | + ) |
| 33 | + |
| 34 | + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 35 | + store, err := session.Start(context.Background(), w, r) |
| 36 | + if err != nil { |
| 37 | + fmt.Fprint(w, err) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + store.Set("foo", "bar") |
| 42 | + err = store.Save() |
| 43 | + if err != nil { |
| 44 | + fmt.Fprint(w, err) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + http.Redirect(w, r, "/foo", 302) |
| 49 | + }) |
| 50 | + |
| 51 | + http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { |
| 52 | + store, err := session.Start(context.Background(), w, r) |
| 53 | + if err != nil { |
| 54 | + fmt.Fprint(w, err) |
| 55 | + return |
| 56 | + } |
| 57 | + |
| 58 | + foo, ok := store.Get("foo") |
| 59 | + if ok { |
| 60 | + fmt.Fprintf(w, "foo:%s", foo) |
| 61 | + return |
| 62 | + } |
| 63 | + fmt.Fprint(w, "does not exist") |
| 64 | + }) |
| 65 | + |
| 66 | + http.ListenAndServe(":8080", nil) |
| 67 | +} |
| 68 | + |
| 69 | +``` |
| 70 | + |
| 71 | +### Build and run |
| 72 | + |
| 73 | +```bash |
| 74 | +$ go build server.go |
| 75 | +$ ./server |
| 76 | +``` |
| 77 | + |
| 78 | +### Open in your web browser |
| 79 | + |
| 80 | +<http://localhost:8080> |
| 81 | + |
| 82 | + foo:bar |
| 83 | + |
| 84 | +## MIT License |
| 85 | + |
| 86 | + Copyright (c) 2018 Lyric |
| 87 | + |
| 88 | +[reportcard-url]: https://goreportcard.com/report/github.com/go-session/mongo |
| 89 | +[reportcard-image]: https://goreportcard.com/badge/github.com/go-session/mongo |
| 90 | +[godoc-url]: https://godoc.org/github.com/go-session/mongo |
| 91 | +[godoc-image]: https://godoc.org/github.com/go-session/mongo?status.svg |
| 92 | +[license-url]: http://opensource.org/licenses/MIT |
| 93 | +[license-image]: https://img.shields.io/npm/l/express.svg |
0 commit comments