-
Notifications
You must be signed in to change notification settings - Fork 30
/
main.go
86 lines (74 loc) · 2.26 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
/*
go build -o codetabs -ldflags="-X 'main.when=$(date -u +%F_%T)'"
*/
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/jolav/codetabs/_utils/stats"
geo "github.com/jolav/codetabs/geolocation"
"github.com/jolav/codetabs/headers"
"github.com/jolav/codetabs/random"
"github.com/jolav/codetabs/ranking"
"github.com/jolav/codetabs/weather"
h "github.com/jolav/codetabs/_utils"
)
var version = "0.11.5"
var when = "undefined"
type config struct {
mode string
port int
storePath string
errorsFilePath string
hitsFilePath string
bannedFilePath string
hitLog *log.Logger
banLog *log.Logger
reloadKey string
}
func main() {
h.CheckFlags(version, when)
c := loadPrivateConfig()
// Custom Error Log File
var mylog *os.File
if c.mode == "production" {
mylog = h.CreateCustomErrorLogFile(c.errorsFilePath)
c.banLog = h.NewBanFile(c.bannedFilePath) // Custom Ban Log File
c.hitLog = h.NewHitsFile(c.hitsFilePath) // Custom Hits Log File
}
defer mylog.Close()
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/geolocation/{format}", mw(geo.Router, "geoip", c))
mux.HandleFunc("GET /v1/headers", mw(headers.Router, "headers", c))
mux.HandleFunc("GET /v1/random/{action}", mw(random.Router, "random", c))
mux.HandleFunc("GET /v1/ranking", mw(ranking.Router, "ranking", c))
mux.HandleFunc("GET /v1/weather", mw(weather.Router, "weather", c))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
go stats.LogHit(r, "-----", c.mode, c.hitLog)
h.SendResponse(w, nil, http.StatusBadRequest)
})
server := http.Server{
Addr: fmt.Sprintf("localhost:%d", c.port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Printf("Server up v%s listening %s in mode %s",
version, server.Addr, c.mode)
server.ListenAndServe()
}
func mw(next http.HandlerFunc, service string, c config) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stats.IsBanned(r, service, c.reloadKey) {
go stats.LogBanned(r, service, c.mode, c.banLog)
h.SendResponse(w, nil, http.StatusUnauthorized)
return
}
go stats.LogHit(r, service, c.mode, c.hitLog)
next.ServeHTTP(w, r)
})
}