package handler import ( "log" "net/http" ) func InternalServerErrorHandler(w http.ResponseWriter, err error) { setError(w, http.StatusInternalServerError, err.Error()) } func NotFoundHandler(w http.ResponseWriter) { setError(w, http.StatusNotFound, "404 Not Found") } func BadRequestHandler(w http.ResponseWriter) { setError(w, http.StatusBadRequest, "404 Not Found") } func UnprocessableEntityHandler(w http.ResponseWriter, err error) { setError(w, http.StatusUnprocessableEntity, err.Error()) } func UnauthorizedHandler(w http.ResponseWriter) { log.Println("unauthorized") setError(w, http.StatusUnauthorized, "Unauthorized") } func NotImplementedHandler(w http.ResponseWriter) { setError(w, http.StatusNotImplemented, "WORK IN PROGRESS") } func setError(w http.ResponseWriter, httpStatus int, errorMessage string) { w.WriteHeader(httpStatus) if _, err := w.Write([]byte(errorMessage)); err != nil { log.Println(err) } return } func handleError(w http.ResponseWriter, status int, err error) bool { if err != nil { switch status { case http.StatusInternalServerError: InternalServerErrorHandler(w, err) case http.StatusNotFound: NotFoundHandler(w) case http.StatusBadRequest: BadRequestHandler(w) case http.StatusUnauthorized: UnauthorizedHandler(w) case http.StatusNotImplemented: NotImplementedHandler(w) case http.StatusUnprocessableEntity: UnprocessableEntityHandler(w, err) default: InternalServerErrorHandler(w, err) } return true } return false }