-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
220 lines (192 loc) · 6.67 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package main
import (
"flag"
"fmt"
"github.com/766b/chi-prometheus"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/render"
"github.com/pedro-gutierrez/form3/pkg/admin"
"github.com/pedro-gutierrez/form3/pkg/health"
"github.com/pedro-gutierrez/form3/pkg/logger"
"github.com/pedro-gutierrez/form3/pkg/payments"
"github.com/pedro-gutierrez/form3/pkg/util"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/ulule/limiter"
"github.com/ulule/limiter/drivers/middleware/stdlib"
"github.com/ulule/limiter/drivers/store/memory"
"log"
"net/http"
"strings"
"time"
)
var (
listen *string
limit *string
compress *bool
metrics *bool
repoDriver *string
repoUri *string
repoMigrations *string
repoSchemaPayments *string
enableCors *bool
timeout *int
adminRoutes *bool
profiling *bool
apiVersion *string
externalUrl *string
maxResults *int
)
func init() {
listen = flag.String("listen", ":8080", "the http interface to listen at")
limit = flag.String("limit", "", "rate limit (eg. 5-S for 5 reqs/second)")
compress = flag.Bool("compress", false, "gzip responses")
metrics = flag.Bool("metrics", false, "expose prometheus metrics")
enableCors = flag.Bool("cors", false, "enable cors")
timeout = flag.Int("timeout", 60, "request timeout")
repoDriver = flag.String("repo", "sqlite3", "type of persistence repository to use, eg. sqlite3, postgres")
repoUri = flag.String("repo-uri", "", "repo specific connection string")
repoMigrations = flag.String("repo-migrations", "./schema", "path to database migrations")
repoSchemaPayments = flag.String("repo-schema-payments", "payments", "the table or schema where we store payments")
adminRoutes = flag.Bool("admin", false, "enable admin endpoints")
profiling = flag.Bool("profiling", false, "enable profiling")
apiVersion = flag.String("api-version", "v1", "api version to expose our services at")
externalUrl = flag.String("external-url", "http://localhost:8080", "url to access our microservice from the outside")
maxResults = flag.Int("max-results", 20, "Maximum number of results when listing items (eg. payments)")
}
// Main entry point to the program. Connects to the database, configures
// all required routes, and starts listening for connections
func main() {
flag.Parse()
// compute the baseUrl as the externalUrl + apiVersion configured in this server
baseUrl := fmt.Sprintf("%s/%s", *externalUrl, *apiVersion)
// Setup our persistence. We do this first, since we want to exit
// the program, in case the database is not available
paymentsRepo, err := util.NewRepo(util.RepoConfig{
Driver: *repoDriver,
Uri: *repoUri,
Migrations: *repoMigrations,
Schema: *repoSchemaPayments,
})
if err != nil {
log.Fatal(errors.Wrap(err, "Could not create repo"))
}
// Initialize the repo. The implementation
// can perform prep work here
err = paymentsRepo.Init()
if err != nil {
log.Fatal(errors.Wrap(err, "Could not init repo"))
}
// Make sure we close the database on exit
defer paymentsRepo.Close()
// Stop here if the repo is not ready
if err := paymentsRepo.Check(); err != nil {
log.Fatal(errors.Wrap(err, "Could connect to the repo"))
}
router := chi.NewRouter()
// Enable default middleware. Please move the ones you'd wish
// to make optional further down.
router.Use(
render.SetContentType(render.ContentTypeJSON),
middleware.Timeout(time.Duration(*timeout)*time.Second),
middleware.RedirectSlashes,
middleware.Recoverer,
middleware.RequestID,
middleware.RealIP,
middleware.AllowContentType("application/json", "text/plain"),
middleware.NoCache,
)
// Maybe turn on Prometheus metrics
if *metrics {
router.Use(chiprometheus.NewMiddleware("payments"))
}
// Use our own structured logger middleware
router.Use(logger.NewHttpLogger())
// Maybe GZIP http responses
if *compress {
router.Use(middleware.DefaultCompress)
}
// Maybe set a rate limit, so that we keep things
// controlled under high load. A 429 status code will
// be returned once we reach the configured threshold.
// For simplicity, we use the memory store but there are other
// options (eg. Redis)
if *limit != "" {
rate, err := limiter.NewRateFromFormatted(*limit)
if err != nil {
log.Fatal(errors.Wrap(err, "Error setting rate limit"))
}
store := memory.NewStore()
router.Use(stdlib.NewMiddleware(limiter.New(store, rate)).Handler)
}
// Set some CORS options, if enabled. I guess the options here could
// be further customised or made configurable
if *enableCors {
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
router.Use(cors.Handler)
}
// If metrics are enabled, then configure the http
// handler. This has to be done after all middleware have been
// set
if *metrics {
router.Mount("/metrics", prometheus.Handler())
}
// If profiling is enabled, enable net/http/pprof middleware
if *profiling {
router.Mount("/profiling", middleware.Profiler())
}
// Mount health probe
router.Mount("/health", health.New(paymentsRepo).Routes())
// Admin features
// (useful for testing, for example, but use with care in a production
// environment
if *adminRoutes {
router.Route("/admin", func(adminRouter chi.Router) {
adminRouter.Mount("/", admin.New(paymentsRepo).Routes())
})
}
// mount application logic
router.Route("/v1", func(v1Router chi.Router) {
// payments api
v1Router.Mount("/", payments.New(paymentsRepo, baseUrl, *maxResults).Routes())
// more endpoints here...
})
// Print all routes mounted
if err := chi.Walk(router, func(method string,
route string,
handler http.Handler,
middlewares ...func(http.Handler) http.Handler) error {
route = strings.Replace(route, "/*/", "/", -1)
logger.Info("Mounted route", &RouteInfo{Method: method, Path: route})
return nil
}); err != nil {
log.Printf(err.Error())
}
// start the server
logger.Info("Started server", &ServerInfo{
ExternalUrl: *externalUrl,
ApiVersion: *apiVersion,
Interface: *listen,
})
log.Fatal(http.ListenAndServe(*listen, router))
}
// Simple route information
type RouteInfo struct {
Method string `json:"method"`
Path string `json:"path"`
}
// Simple port information
type ServerInfo struct {
Interface string `json:"interface"`
ExternalUrl string `json:"externalUrl"`
ApiVersion string `json:"apiVersion"`
}