summaryrefslogtreecommitdiff
path: root/session/bbolt/bbolt.go
diff options
context:
space:
mode:
Diffstat (limited to 'session/bbolt/bbolt.go')
-rw-r--r--session/bbolt/bbolt.go61
1 files changed, 61 insertions, 0 deletions
diff --git a/session/bbolt/bbolt.go b/session/bbolt/bbolt.go
new file mode 100644
index 0000000..8e55d25
--- /dev/null
+++ b/session/bbolt/bbolt.go
@@ -0,0 +1,61 @@
+package bbolt
+
+import (
+ "bytes"
+ "context"
+ "encoding/gob"
+ "log/slog"
+
+ "go.etcd.io/bbolt"
+ "go.neonxp.ru/middleware/session"
+)
+
+func New(db *bbolt.DB, bucketName []byte) session.Store {
+ return &Store{
+ db: db,
+ bucketName: bucketName,
+ }
+}
+
+type Store struct {
+ db *bbolt.DB
+ bucketName []byte
+}
+
+func (s *Store) Load(ctx context.Context, sessionID string) session.Value {
+ v := session.Value{}
+ err := s.db.View(func(tx *bbolt.Tx) error {
+ bucket := tx.Bucket(s.bucketName)
+ if bucket == nil {
+ // no bucket -- normal situation
+ return nil
+ }
+ vb := bucket.Get([]byte(sessionID))
+ if vb == nil {
+ // no session -- no error
+ return nil
+ }
+ rdr := bytes.NewBuffer(vb)
+
+ return gob.NewDecoder(rdr).Decode(&v)
+ })
+ if err != nil {
+ slog.WarnContext(ctx, "failed load session", slog.Any("error", err))
+ }
+ return v
+}
+
+func (s *Store) Save(ctx context.Context, sessionID string, value session.Value) error {
+ return s.db.Update(func(tx *bbolt.Tx) error {
+ bucket, err := tx.CreateBucketIfNotExists(s.bucketName)
+ if err != nil {
+ return err
+ }
+ wrt := bytes.NewBuffer([]byte{})
+ if err := gob.NewEncoder(wrt).Encode(value); err != nil {
+ return err
+ }
+
+ return bucket.Put([]byte(sessionID), wrt.Bytes())
+ })
+}