forked from mr-karan/calert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
158 lines (132 loc) · 4.28 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/gorilla/mux"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
)
var (
// Version of the build.
// This is injected at build-time.
// Be sure to run the provided run script to inject correctly (check Makefile).
version = "unknown"
date = "unknown"
sysLog *log.Logger
errLog *log.Logger
)
// App is the context that's injected into HTTP request handlers.
type App struct {
notifier Notifier
}
// The Handler struct takes App and a function matching
// our useful signature. It is used to pass App as context in handlers
type Handler struct {
*App
HandleRequest func(a *App, w http.ResponseWriter, r *http.Request) (code int, message string, data interface{}, et ErrorType, err error)
}
// ServeHTTP allows our Handler type to satisfy http.Handler so that
// Handler can be used with r.Handle.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
code, msg, data, et, err := h.HandleRequest(h.App, w, r)
if et != "" {
if err != nil {
errLog.Printf("Error while processing request: %s", err)
}
sendErrorEnvelope(w, code, msg, data, et)
} else {
sendEnvelope(w, code, msg, data)
}
}
func initLogger() {
sysLog = log.New(os.Stdout, "SYS: ", log.Ldate|log.Ltime|log.Llongfile)
errLog = log.New(os.Stderr, "ERR: ", log.Ldate|log.Ltime|log.Llongfile)
}
func initConfig() {
// Command line flags.
flagSet := flag.NewFlagSet("config", flag.ContinueOnError)
flagSet.Usage = func() {
fmt.Println(flagSet.FlagUsages())
os.Exit(0)
}
// Config Path flag.
flagSet.String("config.file", "", "Path to config file")
viper.SetDefault("server.address", ":5000")
viper.SetDefault("server.socket", "/tmp/calert.sock")
viper.SetDefault("server.name", "calert")
viper.SetDefault("server.read_timeout", 1000)
viper.SetDefault("server.write_timeout", 5000)
viper.SetDefault("server.keepalive_timeout", 30000)
viper.SetDefault("app.http_client.proxy_url", "")
viper.SetDefault("app.max_size", 4000)
// Process flags.
flagSet.Parse(os.Args[1:])
viper.BindPFlags(flagSet)
// Config file.
// check if config.file flag is passed and read from the file if it is set
configPath := viper.GetString("config.file")
if configPath != "" {
viper.SetConfigFile(configPath)
} else {
// fallback to default config.
viper.SetConfigName("config")
viper.AddConfigPath(".")
}
err := viper.ReadInConfig()
if err != nil {
errLog.Fatalf("Error reading config: %s", err)
}
}
func initClient() *http.Client {
transport := &http.Transport{
MaxIdleConnsPerHost: viper.GetInt("app.http_client.max_idle_conns"),
ResponseHeaderTimeout: time.Duration(viper.GetDuration("app.http_client.request_timeout") * time.Millisecond),
}
proxyURLString := viper.GetString("app.http_client.proxy_url")
if proxyURLString != "" {
proxyURL, err := url.Parse(proxyURLString)
if err != nil {
errLog.Fatalf("Unable to parse `proxy_url`: %s", err)
}
transport.Proxy = http.ProxyURL(proxyURL)
}
// Generic HTTP handler for communicating with the Chat webhook endpoint.
return &http.Client{
Timeout: time.Duration(viper.GetDuration("app.http_client.request_timeout") * time.Millisecond),
Transport: transport}
}
// prog initialisation.
func init() {
initLogger()
initConfig()
}
func main() {
var (
httpClient = initClient()
notifier = NewNotifier(*httpClient)
appConfig = &App{notifier}
)
// init router
r := mux.NewRouter()
r.Handle("/", Handler{appConfig, handleIndex}).Methods("GET")
r.Handle("/create", Handler{appConfig, handleNewAlert}).Methods("POST")
r.Handle("/ping", Handler{appConfig, handleHealthCheck}).Methods("GET")
// TODO : r.HandleFunc("/metrics", handleMetrics).Methods("GET")
// Initialize HTTP server and pass router
s := &http.Server{
Addr: viper.GetString("server.address"),
Handler: r,
ReadTimeout: time.Millisecond * viper.GetDuration("server.read_timeout"),
WriteTimeout: time.Millisecond * viper.GetDuration("server.write_timeout"),
IdleTimeout: time.Millisecond * viper.GetDuration("server.keepalive_timeout"),
}
// Start the web server
sysLog.Printf("listening on %s | %s", viper.GetString("server.address"), viper.GetString("server.socket"))
if err := s.ListenAndServe(); err != nil {
errLog.Fatalf("error starting server: %s", err)
}
}