I’m running a basic http.FileServer
to serve a static site and I’ve come across an issue where requests for css files that don’t exist are getting canceled with a MIME type error:
Refused to apply style from 'http://localhost:8080/assets/main.css' because its MIME type ('text/plain')
Ideally, I’d prefer it to be handled with a 404 error as thats what it should actually be. Any possible work arounds I could try?
From the net/http
source code (fs.go
):
// toHTTPError returns a non-specific HTTP error message and status code
// for a given non-nil error value. It's important that toHTTPError does not
// actually return err.Error(), since msg and httpStatus are returned to users,
// and historically Go's ServeContent always returned just "404 Not Found" for
// all errors. We don't want to start leaking information in error messages.
func toHTTPError(err error) (msg string, httpStatus int) {
if os.IsNotExist(err) {
return "404 page not found", StatusNotFound
}
if os.IsPermission(err) {
return "403 Forbidden", StatusForbidden
}
// Default:
return "500 Internal Server Error", StatusInternalServerError
}
The file server returns a 200 with a plain text file for 404 errors. The browser tries to interpret this plain text error page as a CSS file, and throws the error.
This behavior of returning the plain text file cannot be overridden on the handler returned by FileServer()
.
As has been pointed out already, this isn't really a bug in net/http
.
If this behavior is undesirable for you for some reason, you can explore creating a custom handler for 404 responses, which has been explored in this thread. You could also use a routing library like Gorilla which has overridable behavior for not found pages.