diff --git a/stores/redis/store.go b/stores/redis/store.go index abe1dbf..792ee23 100644 --- a/stores/redis/store.go +++ b/stores/redis/store.go @@ -191,9 +191,29 @@ func (s *Store) Commit(sess *simplesessions.Session, id string) error { // Set to redis conn := s.pool.Get() defer conn.Close() - _, err := conn.Do("HMSET", args...) - return err + conn.Send("MULTI") + conn.Send("HMSET", args...) + + // Set expiry of key only if 'ttl' is set, this is to + // ensure that the key remains valid indefinitely like + // how redis handles it by default + if s.ttl > 0 { + conn.Send("EXPIRE", args[0], s.ttl.Seconds()) + } + + res, err := redis.Values(conn.Do("EXEC")) + if err != nil { + return err + } + + for _, r := range res { + if v, ok := r.(redis.Error); ok { + return v + } + } + + return nil } // Delete deletes a key from redis session hashmap. diff --git a/stores/redis/store_test.go b/stores/redis/store_test.go index 145b6d3..876ae15 100644 --- a/stores/redis/store_test.go +++ b/stores/redis/store_test.go @@ -320,12 +320,14 @@ func TestEmptyCommit(t *testing.T) { } func TestCommit(t *testing.T) { - // Test should only set in internal map and not in redis + // Test should commit in redis with expiry on key assert := assert.New(t) redisPool := getRedisPool() str := New(redisPool) sess := &simplesessions.Session{} + str.SetTTL(10 * time.Second) + // this key is unique across all tests key := "8dIHy6S2uBuKaNnTUszB2180898ikGY1" field1 := "somekey" @@ -346,6 +348,11 @@ func TestCommit(t *testing.T) { defer conn.Close() vals, err := redis.Values(conn.Do("HGETALL", defaultPrefix+key)) assert.Equal(2*2, len(vals)) + + ttl, err := redis.Int(conn.Do("TTL", defaultPrefix+key)) + assert.NoError(err) + + assert.Equal(true, ttl > 0 && ttl <= 10) } func TestDeleteInvalidSessionError(t *testing.T) {