/
main.go
112 lines (95 loc) · 2.04 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
// Copyright 2014 go-beacon authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"runtime"
"syscall"
html "html/template"
text "text/template"
"github.com/fiorix/go-redis/redis"
)
/* app version and name */
var (
VERSION = "tip"
APPNAME = "go-beacon"
HTML *html.Template
TEXT *text.Template
// Producer
producer *Producer
)
func main() {
configFile := flag.String("c", "go-beacon.conf", "")
logFile := flag.String("l", "", "")
flag.Usage = func() {
fmt.Println("Usage: go-beacon [-c go-beacon.conf] [-l logfile]")
os.Exit(1)
}
flag.Parse()
var err error
config, err := loadConfig(*configFile)
if err != nil {
log.Fatal(err)
}
// Initialize log.
if *logFile != "" {
setLog(*logFile)
}
// Parse templates.
HTML = html.Must(html.ParseGlob(config.TemplatesDir + "/*.html"))
TEXT = text.Must(text.ParseGlob(config.TemplatesDir + "/*.txt"))
// Set up databases.
rc := redis.New(config.DB.Redis)
// Set GOMAXPROCS and show server info.
var cpuinfo string
if n := runtime.NumCPU(); n > 1 {
runtime.GOMAXPROCS(n)
cpuinfo = fmt.Sprintf("%d CPUs", n)
} else {
cpuinfo = "1 CPU"
}
log.Printf("%s %s (%s)", APPNAME, VERSION, cpuinfo)
// Start producer
producer = newProducer(config.Backend.BackendURL, config.Backend.FlushInterval)
// Start HTTP server.
s := new(httpServer)
s.init(config, rc)
go s.ListenAndServe()
go s.ListenAndServeTLS()
// Sleep forever.
select {}
}
func setLog(filename string) {
f := openLog(filename)
log.SetOutput(f)
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGHUP)
go func() {
// Recycle log file on SIGHUP.
var fb *os.File
for {
<-sigc
fb = f
f = openLog(filename)
log.SetOutput(f)
fb.Close()
}
}()
}
func openLog(filename string) *os.File {
f, err := os.OpenFile(
filename,
os.O_WRONLY|os.O_CREATE|os.O_APPEND,
0644,
)
if err != nil {
log.SetOutput(os.Stderr)
log.Fatal(err)
}
return f
}