-
Notifications
You must be signed in to change notification settings - Fork 0
/
live.go
71 lines (55 loc) · 1.23 KB
/
live.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
70
71
package main
import (
"encoding/json"
"log"
"os"
"github.com/garyburd/redigo/redis"
)
const (
// Name of redis channel for hits subscription
redisChannel = "hits"
)
type Hit struct {
Host string
Path string
Code string
}
var hits = make(chan Hit)
func main() {
connection := connect()
go listen(connection)
serve()
}
func connect() redis.Conn {
redisAddress := os.Getenv("REDIS_ADDRESS")
redisPassword := os.Getenv("REDIS_PASSWORD")
connection, err := redis.Dial("tcp", redisAddress)
if err != nil {
log.Panic("Eror connecting to redis...", err)
}
if len(redisPassword) > 0 {
err := connection.Send("AUTH", redisPassword)
if err != nil {
log.Panic("Eror authenticating...", err)
}
}
return connection
}
func listen(connection redis.Conn) {
pubSubConnection := redis.PubSubConn{connection}
pubSubConnection.Subscribe(redisChannel)
log.Println("Listening to redis '" + redisChannel + "' channel...")
for {
reply, message := pubSubConnection.Receive().(redis.Message)
if message {
hit := parseMessage(reply)
hits <- hit
log.Print("[" + hit.Code + "] " + hit.Host + hit.Path)
}
}
}
func parseMessage(hitMessage redis.Message) Hit {
var hit Hit
json.Unmarshal(hitMessage.Data, &hit)
return hit
}