forked from monstar-lab/golang-docker-development-env
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredis.go
executable file
·63 lines (52 loc) · 1.12 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/garyburd/redigo/redis"
)
type redisHandler struct{}
func (h redisHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//get the current views count from redis storage
v := getViews()
v++
//set the new views count to redis storage
updateViews(v)
//output the view count to browser
fmt.Fprintf(w, "Viewed count from redis : "+strconv.Itoa(v))
}
//connects to redis service
func redisConnect() redis.Conn {
c, err := redis.Dial("tcp", "redis:6379")
if err != nil {
log.Fatal(err)
}
return c
}
func updateViews(cnt int) {
c := redisConnect()
defer c.Close()
// set the value on redis for the key viewedcount
reply, err := c.Do("SET", "viewedcount", cnt)
if err != nil {
log.Fatal(err)
}
log.Println("GET ", reply)
}
func getViews() int {
c := redisConnect()
defer c.Close()
// get the value from redis for the key viewedcount
reply, err := c.Do("GET", "viewedcount")
if err != nil {
log.Fatal(err)
}
if reply != nil {
s := string(reply.([]byte))
log.Println("GET ", s)
i, _ := strconv.Atoi(s)
return i
}
return 0
}