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

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