Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Heartbeat Middleware for subrouter too #822

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion middleware/heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package middleware
import (
"net/http"
"strings"

"github.com/go-chi/chi/v5"
)

// Heartbeat endpoint middleware useful to setting up a path like
Expand All @@ -12,7 +14,9 @@ import (
func Heartbeat(endpoint string) func(http.Handler) http.Handler {
f := func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if (r.Method == "GET" || r.Method == "HEAD") && strings.EqualFold(r.URL.Path, endpoint) {
rctx := chi.RouteContext(r.Context())
routePath := rctx.RoutePath
if (r.Method == "GET" || r.Method == "HEAD") && (strings.EqualFold(routePath, endpoint)) || strings.EqualFold(r.URL.Path, endpoint) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("."))
Expand Down
47 changes: 47 additions & 0 deletions middleware/heartbeat_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/go-chi/chi/v5"
)

func TestHeartbeat(t *testing.T) {
r := chi.NewRouter()
r.Use(Heartbeat("/ping"))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test", "yes")
w.Write([]byte("bye"))
})
r.Mount("/sub", NewSubrouter())

ts := httptest.NewServer(r)
defer ts.Close()

if _, body := testRequest(t, ts, "GET", "/", nil); body != "bye" {
t.Fatalf(body)
}
if _, body := testRequest(t, ts, "GET", "/ping", nil); body != "." {
t.Fatalf(body)
}
if _, body := testRequest(t, ts, "GET", "/sub", nil); body != "bye" {
t.Fatalf(body)
}
if _, body := testRequest(t, ts, "GET", "/sub/ping", nil); body != "." {
t.Fatalf(body)
}
}

func NewSubrouter() chi.Router {
r := chi.NewRouter()
r.Use(Heartbeat("/ping"))

r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test", "yes")
w.Write([]byte("bye"))
})

return r
}