Skip to content

Commit a14fb33

Browse files
committed
try config as functions
1 parent 39a0d4f commit a14fb33

File tree

3 files changed

+58
-46
lines changed

3 files changed

+58
-46
lines changed

router/options.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package router
2+
3+
import (
4+
"github.com/netlify/netlify-commons/tracing"
5+
"github.com/rs/cors"
6+
"github.com/sirupsen/logrus"
7+
)
8+
9+
type Option func(r Router)
10+
11+
func OptEnableCORS(r Router) {
12+
corsMiddleware := cors.New(cors.Options{
13+
AllowedMethods: []string{"GET", "POST", "PATCH", "PUT", "DELETE"},
14+
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
15+
ExposedHeaders: []string{"Link", "X-Total-Count"},
16+
AllowCredentials: true,
17+
})
18+
r.Use(corsMiddleware.Handler)
19+
}
20+
21+
func OptHealthCheck(path string, checker APIHandler) Option {
22+
return func(r Router) {
23+
r.Use(HealthCheck(path, checker))
24+
}
25+
}
26+
27+
func OptVersionHeader(svcName, version string) Option {
28+
return func(r Router) {
29+
r.Use(VersionHeader(svcName, version))
30+
31+
}
32+
}
33+
34+
func OptTracingMiddleware(log logrus.FieldLogger, svcName string) Option {
35+
return func(r Router) {
36+
r.Use(tracing.Middleware(log, svcName))
37+
}
38+
}
39+
40+

router/router.go

Lines changed: 3 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import (
44
"net/http"
55

66
"github.com/go-chi/chi"
7-
"github.com/netlify/netlify-commons/tracing"
8-
"github.com/rs/cors"
97
"github.com/sebest/xff"
108
"github.com/sirupsen/logrus"
119
)
@@ -14,15 +12,6 @@ type chiWrapper struct {
1412
chi chi.Router
1513
}
1614

17-
// Options configures specifics of the default router
18-
type Options struct {
19-
EnableCORS bool
20-
Version string
21-
HealthCheckPath string
22-
HealthChecker APIHandler
23-
Description string
24-
}
25-
2615
// Router wraps the chi router to make it slightly more accessible
2716
type Router interface {
2817
// Use appends one middleware onto the Router stack.
@@ -47,33 +36,15 @@ type Router interface {
4736
}
4837

4938
// creates a router with sensible defaults (xff, request id, cors)
50-
func New(serviceName string, log logrus.FieldLogger, options Options) Router {
39+
func New(log logrus.FieldLogger, options ...Option) Router {
5140
r := &chiWrapper{chi.NewRouter()}
5241

5342
xffmw, _ := xff.Default()
5443
r.Use(xffmw.Handler)
55-
// r.Use(middlewareFunc(Recoverer)) TODO
56-
57-
if options.EnableCORS {
58-
corsMiddleware := cors.New(cors.Options{
59-
AllowedMethods: []string{"GET", "POST", "PATCH", "PUT", "DELETE"},
60-
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
61-
ExposedHeaders: []string{"Link", "X-Total-Count"},
62-
AllowCredentials: true,
63-
})
64-
r.Use(corsMiddleware.Handler)
44+
for _, opt := range options {
45+
opt(r)
6546
}
6647

67-
if options.HealthCheckPath != "" {
68-
r.Use(HealthCheck(options.HealthCheckPath, options.HealthChecker))
69-
}
70-
71-
version := "unknown"
72-
if options.Version != "" {
73-
version = options.Version
74-
}
75-
r.Use(VersionHeader(serviceName, version))
76-
r.Use(tracing.Middleware(log, serviceName))
7748
return r
7849
}
7950

router/router_test.go

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ func TestCORS(t *testing.T) {
1717
req.Header.Set("Access-Control-Request-Method", "GET")
1818
req.Header.Set("Access-Control-Request-Headers", "Content-Type")
1919
t.Run("enabled", func(t *testing.T) {
20-
rsp := do(t, &Options{EnableCORS: true}, "", "/", nil, req)
20+
rsp := do(t, []Option{OptEnableCORS}, "", "/", nil, req)
2121
assert.Equal(t, http.StatusOK, rsp.Code)
2222
})
2323
t.Run("disabled", func(t *testing.T) {
@@ -45,17 +45,20 @@ func TestHealthEndpoint(t *testing.T) {
4545
require.NoError(t, err)
4646

4747
scenarios := map[string]struct {
48-
opts *Options
48+
opts []Option
4949
code int
5050
}{
51-
"disabled": {&Options{HealthCheckPath: ""}, http.StatusNotFound},
52-
"default": {&Options{HealthCheckPath: "/health"}, http.StatusOK},
53-
"custom": {&Options{
54-
HealthCheckPath: "/health",
55-
HealthChecker: func(_ http.ResponseWriter, r *http.Request) *HTTPError {
51+
"disabled": {[]Option{OptHealthCheck("", nil)}, http.StatusNotFound},
52+
"default": {[]Option{OptHealthCheck("/health", nil)}, http.StatusOK},
53+
"custom": {[]Option{OptHealthCheck(
54+
"/health",
55+
func(_ http.ResponseWriter, r *http.Request) *HTTPError {
5656
return UnauthorizedError("")
57-
}}, http.StatusUnauthorized},
57+
})},
58+
http.StatusUnauthorized},
5859
}
60+
61+
5962
for name, scene := range scenarios {
6063
t.Run(name, func(t *testing.T) {
6164
rsp := do(t, scene.opts, "", "/", nil, req)
@@ -79,20 +82,18 @@ func TestVersionHeader(t *testing.T) {
7982
for name, scene := range scenes {
8083

8184
t.Run(name, func(t *testing.T) {
82-
opts := &Options{
83-
Version: scene.version,
84-
}
85+
opts := []Option{OptVersionHeader(scene.svc, scene.version)}
8586
rsp := do(t, opts, scene.svc, "/", nil, req)
8687
assert.Equal(t, scene.expected, rsp.Header().Get(scene.header), t.Name())
8788
})
8889
}
8990
}
9091

91-
func do(t *testing.T, opts *Options, svcName, path string, handler APIHandler, req *http.Request) *httptest.ResponseRecorder {
92+
func do(t *testing.T, opts []Option, svcName, path string, handler APIHandler, req *http.Request) *httptest.ResponseRecorder {
9293
if opts == nil {
93-
opts = new(Options)
94+
opts = []Option{}
9495
}
95-
r := New(svcName, logrus.WithField("test", t.Name()), *opts)
96+
r := New(logrus.WithField("test", t.Name()), opts...)
9697

9798
if handler == nil {
9899
handler = func(w http.ResponseWriter, r *http.Request) *HTTPError {

0 commit comments

Comments
 (0)