forked from davemachado/public-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (72 loc) · 1.82 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
package main
import (
"io"
"log"
"net/http"
"os"
"strconv"
"github.com/didip/tollbooth"
"github.com/didip/tollbooth_negroni"
"github.com/urfave/negroni"
)
var apiList Entries
var categories []string
func main() {
jsonFile := os.Getenv("JSONFILE")
if jsonFile == "" {
jsonFile = "/entries.json"
}
getList(jsonFile)
categories = parseCategories(apiList.Entries)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
rate := os.Getenv("RATE")
if rate == "" {
rate = "10"
}
i, err := strconv.Atoi(rate)
if err != nil {
panic(err)
}
limiter := tollbooth.NewLimiter(float64(i), nil)
filename := os.Getenv("LOGFILE")
if filename == "" {
filename = "/tmp/public-api.log"
}
// If the file does not exist, create it. Otherwise, append to the file.
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
logger := NewLogger(Options{
Out: io.MultiWriter(f, os.Stdout),
})
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("./static")))
mux.Handle("/entries", negroni.New(
tollbooth_negroni.LimitHandler(limiter),
negroni.Wrap(getEntriesHandler()),
))
mux.Handle("/categories", negroni.New(
tollbooth_negroni.LimitHandler(limiter),
negroni.Wrap(getCategoriesHandler()),
))
mux.Handle("/random", negroni.New(
tollbooth_negroni.LimitHandler(limiter),
negroni.Wrap(getRandomHandler()),
))
mux.Handle("/health", negroni.New(
tollbooth_negroni.LimitHandler(limiter),
negroni.Wrap(healthCheckHandler()),
))
n := negroni.New(negroni.HandlerFunc(logger.logFunc), negroni.HandlerFunc(encodeURL))
recovery := negroni.NewRecovery()
recovery.PrintStack = false
n.Use(recovery)
n.UseHandler(mux)
log.Println("logging requests in " + filename)
log.Printf("listening on port %s\n", port)
log.Fatal(http.ListenAndServe(":"+port, n))
}