From 0290221a0ca0e46b3fa19f7fdb5eb3ac41e2a98d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Tue, 4 Jun 2024 22:45:20 +0200 Subject: [PATCH] Relax ThenFunc signature to allow any HandlerFunc Relax ThenFunc signature to allow any HandlerFunc (based on the anonymous func type of HandlerFunc) not just those with the http.HandlerFunc concrete type. This gives more flexibility to users of the chain API. While this can be considered a breaking change (the ThenFunc signature is not strictly the same), the new signature widens the accepted input values for ThenFunc. --- chain.go | 7 +++---- chain_test.go | 3 +++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/chain.go b/chain.go index f00f12a..77adac0 100644 --- a/chain.go +++ b/chain.go @@ -69,13 +69,12 @@ func (c Chain) Then(h http.Handler) http.Handler { // c.ThenFunc(fn) // // ThenFunc provides all the guarantees of Then. -func (c Chain) ThenFunc(fn http.HandlerFunc) http.Handler { - // This nil check cannot be removed due to the "nil is not nil" common mistake in Go. - // Required due to: https://stackoverflow.com/questions/33426977/how-to-golang-check-a-variable-is-nil +func (c Chain) ThenFunc(fn func(http.ResponseWriter, *http.Request)) http.Handler { + // We want to preserve the special behavior similar to Then(nil) if fn == nil { return c.Then(nil) } - return c.Then(fn) + return c.Then(http.HandlerFunc(fn)) } // Append extends a chain, adding the specified constructors diff --git a/chain_test.go b/chain_test.go index c486553..392e0da 100644 --- a/chain_test.go +++ b/chain_test.go @@ -67,6 +67,9 @@ func TestThenFuncTreatsNilAsDefaultServeMux(t *testing.T) { if New().ThenFunc(nil) != http.DefaultServeMux { t.Error("ThenFunc does not treat nil as DefaultServeMux") } + if New().ThenFunc(http.HandlerFunc(nil)) != http.DefaultServeMux { + t.Error("ThenFunc does not treat nil as DefaultServeMux") + } } func TestThenFuncConstructsHandlerFunc(t *testing.T) {