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 }