diff --git a/README.md b/README.md new file mode 100644 index 0000000..e1cc76b --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ + + +```go +import ( + "github.com/dalu/mongostore" +) + + func main() { + ctx := context.Background() + client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) + err = client.Ping(ctx, readpref.Primary()) + if err != nil { + panic(err) + } + + store := mongostore.NewMongoStore(client, "test", "sessions", 3*time.Second, []byte("hellol-worlol")) + store.Options.Path = "/" + store.Options.MaxAge = 86400 * 30 * 365 + defer store.Close() + + // Get a session. + session, err := store.Get(req, "session-key") + if err != nil { + log.Println(err.Error()) + } + + // Add a value. + session.Values["foo"] = "bar" + + // Save. + if err = sessions.Save(req, rw); err != nil { + log.Printf("Error saving session: %v", err) + } + } +``` \ No newline at end of file diff --git a/store_test.go b/store_test.go index eaa1674..b94e7bc 100644 --- a/store_test.go +++ b/store_test.go @@ -13,6 +13,7 @@ import ( "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" + "log" "net/http" "net/http/httptest" "testing" @@ -199,6 +200,37 @@ func TestFlashes(t *testing.T) { } } +func TestNewMongoStore(t *testing.T) { + ctx := context.Background() + client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) + err = client.Ping(ctx, readpref.Primary()) + if err != nil { + panic(err) + } + + store := mongostore.NewMongoStore(client, "test", "sessions", 3*time.Second, []byte("hellol-worlol")) + store.Options.Path = "/" + store.Options.MaxAge = 86400 * 30 * 365 + defer store.Close() + + req, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + rsp := NewRecorder() + + // Get a session. + session, err := store.Get(req, "session-key") + if err != nil { + log.Println(err.Error()) + } + + // Add a value. + session.Values["foo"] = "bar" + + // Save. + if err = sessions.Save(req, rsp); err != nil { + log.Printf("Error saving session: %v", err) + } +} + func init() { gob.Register(FlashMessage{}) }