forked from arachnys/athenapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (76 loc) · 2.37 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
package main
import (
"github.com/DeanThompson/ginpprof"
"github.com/arachnys/athenapdf/weaver/converter"
"github.com/getsentry/raven-go"
"github.com/gin-gonic/contrib/sentry"
"github.com/gin-gonic/gin"
"gopkg.in/alexcesaro/statsd.v2"
"time"
)
// InitMiddleware sets up the necessary middlewares for the microservice.
// These include middlewares to establish a sane context containing access to
// the configuration, worker queue, statsd client, and Sentry client (Raven).
// The latter two are disabled in debugging mode to avoid contaminating
// production stats.
// It will also set up a middleware for catching, and handling errors thrown
// from a route.
func InitMiddleware(router *gin.Engine, conf Config) {
// Config
router.Use(ConfigMiddleware(conf))
// Worker queue
wq := converter.InitWorkers(conf.MaxWorkers, conf.MaxConversionQueue, conf.WorkerTimeout)
router.Use(WorkQueueMiddleware(wq))
// Statsd
muteStatsd := gin.IsDebugging()
if conf.Statsd.Address == "" {
muteStatsd = true
}
s, err := statsd.New(
statsd.Address(conf.Statsd.Address),
statsd.Prefix(conf.Statsd.Prefix),
statsd.FlushPeriod(time.Millisecond*500),
statsd.Mute(muteStatsd),
)
if err != nil {
panic(err)
}
router.Use(StatsdMiddleware(s))
// Sentry (crash reporting)
if !gin.IsDebugging() && conf.SentryDSN != "" {
r, err := raven.New(conf.SentryDSN)
if err != nil {
panic(err)
}
router.Use(SentryMiddleware(r))
router.Use(sentry.Recovery(r, true))
}
// Error handler
router.Use(ErrorMiddleware())
}
// InitSecureRoutes creates the necessary conversion routes with a middleware
// to restrict access via an auth key (defined in the environment config).
func InitSecureRoutes(router *gin.Engine, conf Config) {
authorized := router.Group("/")
authorized.Use(AuthorizationMiddleware(conf.AuthKey))
authorized.GET("/convert", convertByURLHandler)
authorized.POST("/convert", convertByFileHandler)
}
// InitSimpleRoutes creates non-essential routes for monitoring and/or
// debugging.
func InitSimpleRoutes(router *gin.Engine, conf Config) {
router.GET("/", indexHandler)
router.GET("/stats", statsHandler)
if gin.IsDebugging() {
ginpprof.Wrapper(router)
}
}
func main() {
router := gin.Default()
// Get config vars from the environment
conf := NewEnvConfig()
InitMiddleware(router, conf)
InitSecureRoutes(router, conf)
InitSimpleRoutes(router, conf)
router.Run(":8080")
}