These steps cover writing and running your application:
- From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter6/redis and navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter6/redis
You should see a file called go.mod that containing the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter6/redis
- Copy tests from ~/projects/go-programming-cookbook-original/chapter6/redis, or use this as an exercise to write some code of your own!
- Create a file called config.go with the following content:
package redis
import (
"os"
redis "gopkg.in/redis.v5"
)
// Setup initializes a redis client
func Setup() (*redis.Client, error) {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: os.Getenv("REDISPASSWORD"),
DB: 0, // use default DB
})
_, err := client.Ping().Result()
return client, err
}
- Create a file called exec.go with the following content:
package redis
import (
"fmt"
"time"
redis "gopkg.in/redis.v5"
)
// Exec performs some redis operations
func Exec() error {
conn, err := Setup()
if err != nil {
return err
}
c1 := "value"
// value is an interface, we can store whatever
// the last argument is the redis expiration
conn.Set("key", c1, 5*time.Second)
var result string
if err := conn.Get("key").Scan(&result); err != nil {
switch err {
// this means the key
// was not found
case redis.Nil:
return nil
default:
return err
}
}
fmt.Println("result =", result)
return nil
}
- Create a file called sort.go with the following content:
package redis
import (
"fmt"
redis "gopkg.in/redis.v5"
)
// Sort performs a sort redis operations
func Sort() error {
conn, err := Setup()
if err != nil {
return err
}
listkey := "list"
if err := conn.LPush(listkey, 1).Err(); err != nil {
return err
}
// this will clean up the list key if any of the subsequent commands error
defer conn.Del(listkey)
if err := conn.LPush(listkey, 3).Err(); err != nil {
return err
}
if err := conn.LPush(listkey, 2).Err(); err != nil {
return err
}
res, err := conn.Sort(listkey, redis.Sort{Order: "ASC"}).Result()
if err != nil {
return err
}
fmt.Println(res)
return nil
}
- Navigate to example.
- Create a file called main.go with the following content:
package main
import "PacktPublishing/
Go-Programming-Cookbook-Second-Edition/
go-cookbook/chapter6/redis"
func main() {
if err := redis.Exec(); err != nil {
panic(err)
}
if err := redis.Sort(); err != nil {
panic(err)
}
}
- Run go run main.go.
- You could also run the following command:
$ go build
$ ./example
You should see the following output:
$ go run main.go
result = value
[1 2 3]
- The go.mod file may be updated and go.sum file should now be present in the top-level recipe directory.
- If you copied or wrote your own tests, go up one directory and run go test. Ensure that all tests pass.