commit 7c06c3c6d8b2268293b7f9a1be63fab8db9ed0ac Author: Anton Zadvorny Date: Wed Sep 30 19:40:06 2020 +0300 Initial commit diff --git a/app_info.go b/app_info.go new file mode 100644 index 0000000..6eaca73 --- /dev/null +++ b/app_info.go @@ -0,0 +1,19 @@ +package middleware + +import ( + "net/http" +) + +// AppInfo adds application name and version headers to the response +func AppInfo(name string, version string) func(http.Handler) http.Handler { + return func(h http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("App-Name", name) + w.Header().Set("App-Version", version) + + h.ServeHTTP(w, r) + } + + return http.HandlerFunc(fn) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..986f501 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module go.pkg.cx/middleware + +go 1.15 diff --git a/ping.go b/ping.go new file mode 100644 index 0000000..6a4c15a --- /dev/null +++ b/ping.go @@ -0,0 +1,23 @@ +package middleware + +import ( + "net/http" + "strings" +) + +// Ping responses with pong to /ping request and stops chain +func Ping(next http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" && strings.HasSuffix(strings.ToLower(r.URL.Path), "/ping") { + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusOK) + w.Write([]byte("pong")) // nolint:errcheck + + return + } + + next.ServeHTTP(w, r) + } + + return http.HandlerFunc(fn) +}