add error handler middleware

This commit is contained in:
Leandro Moreira
2024-01-29 16:31:34 -03:00
parent 5bfd75f3d8
commit 89b63f1809
4 changed files with 32 additions and 90 deletions

View File

@@ -4,17 +4,23 @@ import (
"net/http"
"github.com/flavioribeiro/donut/internal/web/handlers"
"go.uber.org/zap"
)
type ErrorHTTPHandler interface {
ServeHTTP(w http.ResponseWriter, r *http.Request) error
}
func NewServeMux(
index *handlers.IndexHandler,
signaling *handlers.SignalingHandler,
l *zap.Logger,
) *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("/", index)
mux.Handle("/doSignaling", setCors(signaling))
mux.Handle("/doSignaling", setCors(errorHandler(l, signaling)))
mux.Handle("/demo", http.FileServer(http.Dir("./demo")))
return mux
@@ -32,3 +38,13 @@ func setCors(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
func errorHandler(l *zap.Logger, next ErrorHTTPHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := next.ServeHTTP(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
}