-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
51 lines (40 loc) · 1.04 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
package main
import (
"fmt"
"net/http"
"os"
"github.com/gomodule/redigo/redis"
)
func setupRedis() bool {
redisHost := os.Getenv("REDISHOST")
redisPort := os.Getenv("REDISPORT")
if len(redisHost) < 1 || len(redisPort) < 1 {
return false
}
redisAddr := fmt.Sprintf("%s:%s", redisHost, redisPort)
const maxConnections = 10
redisPool = redis.NewPool(func() (redis.Conn, error) {
return redis.Dial("tcp", redisAddr)
}, maxConnections)
return true
}
func incrementHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx, span := startSpan(ctx, "redis/increment")
defer span.End()
conn := redisPool.Get()
defer func() {
if err := conn.Close(); err != nil {
fmt.Printf("warning: conn.Close() err=%+v\n", err)
}
}()
counter, err := redis.Int(conn.Do("INCR", "visits"))
if err != nil {
http.Error(w, "Error incrementing visitor counter", http.StatusInternalServerError)
return
}
_, err = fmt.Fprintf(w, "Visitor number: %d", counter)
if err != nil {
fmt.Printf("failed write to response. err=%v\n", err)
}
}