github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume2/section5/gopherfacedb/common/datastore/redis.go (about)

     1  package datastore
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"log"
     7  
     8  	"github.com/EngineerKamesh/gofullstack/volume2/section5/gopherfacedb/models"
     9  
    10  	"github.com/mediocregopher/radix.v2/pool"
    11  )
    12  
    13  type RedisDatastore struct {
    14  	*pool.Pool
    15  }
    16  
    17  func NewRedisDatastore(address string) (*RedisDatastore, error) {
    18  
    19  	connectionPool, err := pool.New("tcp", address, 10)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	return &RedisDatastore{
    24  		Pool: connectionPool,
    25  	}, nil
    26  }
    27  
    28  func (r *RedisDatastore) CreateUser(user *models.User) error {
    29  
    30  	userJSON, err := json.Marshal(*user)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	if r.Cmd("SET", "user:"+user.Username, string(userJSON)).Err != nil {
    36  		return errors.New("Failed to execute Redis SET command")
    37  	}
    38  
    39  	return nil
    40  }
    41  
    42  func (r *RedisDatastore) GetUser(username string) (*models.User, error) {
    43  
    44  	exists, err := r.Cmd("EXISTS", "user:"+username).Int()
    45  
    46  	if err != nil {
    47  		return nil, err
    48  	} else if exists == 0 {
    49  		return nil, nil
    50  	}
    51  
    52  	var u models.User
    53  
    54  	userJSON, err := r.Cmd("GET", "user:"+username).Str()
    55  
    56  	if err != nil {
    57  		log.Print(err)
    58  
    59  		return nil, err
    60  	}
    61  
    62  	if err := json.Unmarshal([]byte(userJSON), &u); err != nil {
    63  		log.Print(err)
    64  		return nil, err
    65  	}
    66  
    67  	return &u, nil
    68  }
    69  
    70  func (r *RedisDatastore) Close() {
    71  
    72  	r.Empty()
    73  }