goshort/internal/util/handler/chain.go
2023-08-17 14:14:59 -03:00

35 lines
963 B
Go

package handlerutils
import (
"net/http"
"github.com/go-chi/chi/v5/middleware"
)
// chainHandlers chains multiple handlers together, and returns a handler
// that will call each handler in order, until one of them writes a response.
func chainHandlers(handlers ...http.Handler) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Create a new CheckWrittenWriter
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
// For each handler, call it and check if the response was written
for _, handler := range handlers {
handler.ServeHTTP(ww, r)
// If the response was written, stop the chain
if ww.Status() != 0 {
return
}
}
}
}
// NewChainedHandler returns a new handler that will call each handler in order,
// until one of them writes a response.
func NewChainedHandler(handlers ...http.Handler) http.Handler {
return http.HandlerFunc(
chainHandlers(handlers...),
)
}