-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (59 loc) · 1.43 KB
/
main.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
64
65
66
67
68
69
/* Author: Mecu Sorin Phone: 0040747020102 */
package main
import (
"fmt"
"html"
"log"
"net/http"
"os"
"time"
"github.com/mediocregopher/radix.v2/redis"
)
const redisHits = "hits"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Print(".")
conn, err := connectToRedis()
if err != nil {
fmt.Fprintf(w, "Error connecting Redis: %+v", err)
return
}
defer conn.Close()
n, err := os.Hostname()
if nil != err {
log.Fatal(err)
}
fmt.Fprintf(w, "Hello from %q.\nThe requested URL is %q\n", n, html.EscapeString(r.URL.Path))
hits, err := conn.Cmd("INCR", redisHits).Int()
if nil != err {
fmt.Fprintf(w, "Failed to reach the Redis server: %+v\n", err)
} else {
fmt.Fprintf(w, "Touched the page %d times\n", hits)
}
})
fmt.Println("Listening on port 5000 ...")
log.Fatal(http.ListenAndServe(":5000", nil))
}
func connectToRedis() (*redis.Client, error) {
ticker := time.NewTicker(200 * time.Millisecond)
timeout := time.NewTimer(5 * time.Second)
defer func() {
ticker.Stop()
timeout.Stop()
}()
err := fmt.Errorf("Didn't try to connect Redis")
for {
select {
case <-ticker.C:
{
fmt.Println("Dialing Redis")
redisConn, err := redis.Dial("tcp", "redis:6379")
if nil == err {
return redisConn, err
}
}
case <-timeout.C:
return nil, fmt.Errorf("Timeout in connecting to Redis because (last error: %+v)", err.Error())
}
}
}