-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdrain.go
More file actions
98 lines (79 loc) · 2.16 KB
/
drain.go
File metadata and controls
98 lines (79 loc) · 2.16 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"github.com/ryanlower/drain/parser"
"github.com/ryanlower/drain/reporters"
)
// Drain is used to maintain a list of Reporters
// registered to recieve parsed logs for processing
type Drain struct {
reporters []reporters.Reporter
}
// AddReporter adds a reporter of type t
// to the list of drain reporters
func (d *Drain) AddReporter(t string) error {
reporter, err := reporters.New(t)
if err != nil {
panic(err)
}
d.reporters = append(d.reporters, reporter)
return nil
}
// Handler takes a http.Request,
// checks authorization via HTTP basic auth (if setup, see authenticated)
// parses the request into a parser.ParsedLogLine via parser.Parse
// and sends the ParsedLogLine to registered Reporters
// If all goes well, writes an OK status to the http.ResponseWriter
func (d *Drain) Handler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if !authenticated(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// TODO, don't break if no body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Panic(err)
http.Error(w, err.Error(), http.StatusBadRequest)
}
parsed, err := parser.Parse(body)
if parsed != nil {
d.report(parsed)
}
w.WriteHeader(http.StatusOK)
}
func (d *Drain) report(hit *parser.ParsedLogLine) {
for _, reporter := range d.reporters {
go reporter.Report(hit)
}
}
// Listens for logs at /drain on env PORT
func main() {
port := os.Getenv("PORT")
drain := new(Drain)
// use Log and Redis reporters by default
// TODO, allow customization
drain.AddReporter("log")
drain.AddReporter("redis")
http.HandleFunc("/drain", drain.Handler)
log.Printf("Listening on port %v ...", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Panic(err)
}
}
// Helper HTTP basic auth function
// Returns false if AUTH_PASSWORD env is set and provided password doesn't match
// true otherwise
func authenticated(r *http.Request) bool {
auth := os.Getenv("AUTH_PASSWORD")
_, password, _ := r.BasicAuth()
if auth != "" && auth != password {
// AUTH_PASSWORD is set and provided password doesn't match
return false
}
return true
}