package httphelpers import ( "errors" "fmt" "net/http" "github.com/minio/minio-go/v6" ) var ErrorBadRequest = errors.New("bad request") var ErrorMethodNotAllowed = errors.New("method not allowed") var ErrorNotFound = errors.New("not found") var ErrorUnauthorized = errors.New("unauthorized") func ErrorResponse(w http.ResponseWriter, err error) { if err == nil { panic("Sneaky, you called ErrorResponse without an error. I shall destroy you") } errorMessage := err.Error() errorStatus := http.StatusInternalServerError if errors.Is(err, ErrorBadRequest) { errorStatus = http.StatusBadRequest } if errors.Is(err, ErrorMethodNotAllowed) { errorStatus = http.StatusMethodNotAllowed } if errors.Is(err, ErrorNotFound) { errorStatus = http.StatusNotFound } var minioErrorResponse minio.ErrorResponse if errors.As(err, &minioErrorResponse) { if minioErrorResponse.Code == "NoSuchKey" { errorStatus = http.StatusNotFound } if minioErrorResponse.Code == "NoSuchBucket" { errorStatus = http.StatusNotFound } // Do not handle MinIO AccessDenied: that's a server error. Our credentials should always be correct } // Let Header.Write() handle escaping w.Header().Add("X-Debug-Error", errorMessage) w.WriteHeader(errorStatus) } func ErrorFromStatus(code int) error { if code == http.StatusOK { return nil } if code == http.StatusNotFound { return ErrorNotFound } if code == http.StatusBadRequest { return ErrorBadRequest } if code == http.StatusUnauthorized { return ErrorUnauthorized } return fmt.Errorf("%s", http.StatusText(code)) }