mirror of
https://github.com/flavioribeiro/donut.git
synced 2025-10-23 23:14:07 +08:00
add error handler middleware
This commit is contained in:
@@ -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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user