extract http error handling
1 file changed, 43 insertions(+), 0 deletions(-)
changed files
A internal/http/mux.go
@@ -0,0 +1,43 @@ +package http + +import ( + "net/http" + + "go.alanpearce.eu/x/log" +) + +type WebHandler func(http.ResponseWriter, *http.Request) *Error +type ErrorHandler func(*Error, http.ResponseWriter, *http.Request) + +type ServeMux struct { + log *log.Logger + errorHandler ErrorHandler + *http.ServeMux +} + +func NewServeMux() *ServeMux { + return &ServeMux{ + ServeMux: http.NewServeMux(), + errorHandler: func(err *Error, w http.ResponseWriter, _ *http.Request) { + http.Error(w, err.Message, err.Code) + }, + } +} + +func (sm *ServeMux) HandleFunc(pattern string, handler WebHandler) { + sm.ServeMux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { + defer func() { + if fail := recover(); fail != nil { + w.WriteHeader(http.StatusInternalServerError) + sm.log.Error("runtime panic!", "error", fail) + } + }() + if err := handler(w, r); err != nil { + sm.errorHandler(err, w, r) + } + }) +} + +func (sm *ServeMux) HandleError(fn ErrorHandler) { + sm.errorHandler = fn +}