From 11c4b26c0b077b1235d607eb488886940726d797 Mon Sep 17 00:00:00 2001 From: Hector Date: Wed, 21 Jun 2023 10:58:43 +0000 Subject: [PATCH] refactor: move server setup code to new package (!90) * Move code setting up the HTTP server to it's own package * This helps clean up the `main` function and make it easier to read * Rename the `BasicAuthMiddleware` to remove reference to Basic since it can now handle any type of auth type https://gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/-/merge_requests/90 --- exporter.go | 42 +-------------------- server/{middleware.go => auth.go} | 2 +- server/{middleware_test.go => auth_test.go} | 8 ++-- server/handler.go | 33 ++++++++++++++++ server/server.go | 33 ++++++++++++++++ 5 files changed, 72 insertions(+), 46 deletions(-) rename server/{middleware.go => auth.go} (72%) rename server/{middleware_test.go => auth_test.go} (74%) create mode 100644 server/handler.go create mode 100644 server/server.go diff --git a/exporter.go b/exporter.go index 6bc0126..e3947c9 100644 --- a/exporter.go +++ b/exporter.go @@ -3,23 +3,17 @@ package main import ( "fmt" "log" - "net/http" "os" "os/signal" "syscall" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/cfg" "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/collector/f2b" "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/collector/textfile" "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/server" ) -const ( - metricsPath = "/metrics" -) - var ( version = "dev" commit = "none" @@ -32,26 +26,6 @@ func printAppVersion() { fmt.Printf(" build date: %s\r\n commit hash: %s\r\n built by: %s\r\n", date, commit, builtBy) } -func rootHtmlHandler(w http.ResponseWriter, r *http.Request) { - _, err := w.Write([]byte( - ` - Fail2Ban Exporter - -

Fail2Ban Exporter

-

Metrics

- - `)) - if err != nil { - log.Printf("error handling root url: %v", err) - w.WriteHeader(http.StatusInternalServerError) - } -} - -func metricHandler(w http.ResponseWriter, r *http.Request, collector *textfile.Collector) { - promhttp.Handler().ServeHTTP(w, r) - collector.WriteTextFileMetrics(w, r) -} - func main() { appSettings := cfg.Parse() if appSettings.VersionMode { @@ -67,21 +41,7 @@ func main() { textFileCollector := textfile.NewCollector(appSettings) prometheus.MustRegister(textFileCollector) - http.HandleFunc("/", server.BasicAuthMiddleware(rootHtmlHandler, appSettings.AuthProvider)) - http.HandleFunc(metricsPath, server.BasicAuthMiddleware( - func(w http.ResponseWriter, r *http.Request) { - metricHandler(w, r, textFileCollector) - }, - appSettings.AuthProvider, - )) - log.Printf("metrics available at '%s'", metricsPath) - - svrErr := make(chan error) - go func() { - svrErr <- http.ListenAndServe(appSettings.MetricsAddress, nil) - }() - log.Print("ready") - + svrErr := server.StartServer(appSettings, textFileCollector) err := <-svrErr log.Fatal(err) } diff --git a/server/middleware.go b/server/auth.go similarity index 72% rename from server/middleware.go rename to server/auth.go index 7593bbc..6ed42ea 100644 --- a/server/middleware.go +++ b/server/auth.go @@ -6,7 +6,7 @@ import ( "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/auth" ) -func BasicAuthMiddleware(handlerFunc http.HandlerFunc, authProvider auth.AuthProvider) http.HandlerFunc { +func AuthMiddleware(handlerFunc http.HandlerFunc, authProvider auth.AuthProvider) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if authProvider.IsAllowed(r) { handlerFunc.ServeHTTP(w, r) diff --git a/server/middleware_test.go b/server/auth_test.go similarity index 74% rename from server/middleware_test.go rename to server/auth_test.go index 3ac564b..5a460c9 100644 --- a/server/middleware_test.go +++ b/server/auth_test.go @@ -18,13 +18,13 @@ func newTestRequest() *http.Request { return httptest.NewRequest(http.MethodGet, "http://example.com", nil) } -func executeBasicAuthMiddlewareTest(t *testing.T, authMatches bool, expectedCode int, expectedCallCount int) { +func executeAuthMiddlewareTest(t *testing.T, authMatches bool, expectedCode int, expectedCallCount int) { callCount := 0 testHandler := func(w http.ResponseWriter, r *http.Request) { callCount++ } - handler := BasicAuthMiddleware(testHandler, testAuthProvider{match: authMatches}) + handler := AuthMiddleware(testHandler, testAuthProvider{match: authMatches}) recorder := httptest.NewRecorder() request := newTestRequest() handler.ServeHTTP(recorder, request) @@ -38,9 +38,9 @@ func executeBasicAuthMiddlewareTest(t *testing.T, authMatches bool, expectedCode } func Test_GIVEN_MatchingBasicAuth_WHEN_MethodCalled_THEN_RequestProcessed(t *testing.T) { - executeBasicAuthMiddlewareTest(t, true, http.StatusOK, 1) + executeAuthMiddlewareTest(t, true, http.StatusOK, 1) } func Test_GIVEN_NonMatchingBasicAuth_WHEN_MethodCalled_THEN_RequestRejected(t *testing.T) { - executeBasicAuthMiddlewareTest(t, false, http.StatusUnauthorized, 0) + executeAuthMiddlewareTest(t, false, http.StatusUnauthorized, 0) } diff --git a/server/handler.go b/server/handler.go new file mode 100644 index 0000000..a0d8bf2 --- /dev/null +++ b/server/handler.go @@ -0,0 +1,33 @@ +package server + +import ( + "log" + "net/http" + + "github.com/prometheus/client_golang/prometheus/promhttp" + "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/collector/textfile" +) + +const ( + metricsPath = "/metrics" +) + +func rootHtmlHandler(w http.ResponseWriter, r *http.Request) { + _, err := w.Write([]byte( + ` + Fail2Ban Exporter + +

Fail2Ban Exporter

+

Metrics

+ + `)) + if err != nil { + log.Printf("error handling root url: %v", err) + w.WriteHeader(http.StatusInternalServerError) + } +} + +func metricHandler(w http.ResponseWriter, r *http.Request, collector *textfile.Collector) { + promhttp.Handler().ServeHTTP(w, r) + collector.WriteTextFileMetrics(w, r) +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..18f2b9f --- /dev/null +++ b/server/server.go @@ -0,0 +1,33 @@ +package server + +import ( + "log" + "net/http" + + "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/cfg" + "gitlab.com/hectorjsmith/fail2ban-prometheus-exporter/collector/textfile" +) + +func StartServer( + appSettings *cfg.AppSettings, + textFileCollector *textfile.Collector, +) chan error { + http.HandleFunc("/", AuthMiddleware( + rootHtmlHandler, + appSettings.AuthProvider, + )) + http.HandleFunc(metricsPath, AuthMiddleware( + func(w http.ResponseWriter, r *http.Request) { + metricHandler(w, r, textFileCollector) + }, + appSettings.AuthProvider, + )) + log.Printf("metrics available at '%s'", metricsPath) + + svrErr := make(chan error) + go func() { + svrErr <- http.ListenAndServe(appSettings.MetricsAddress, nil) + }() + log.Print("ready") + return svrErr +}