net/http: using errors.Is in fs error detection

Compare error by errors.Is to detect wrapped fs errors.

Fixes #44923
This commit is contained in:
Peng Gao 2021-03-31 14:45:03 +00:00
parent 565e70fcef
commit dba01ddae0
2 changed files with 9 additions and 7 deletions

View file

@ -46,7 +46,7 @@ type Dir string
// to a possibly better non-nil error. In particular, it turns OS-specific errors
// about opening files in non-directories into fs.ErrNotExist. See Issue 18984.
func mapDirOpenError(originalErr error, name string) error {
if os.IsNotExist(originalErr) || os.IsPermission(originalErr) {
if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) {
return originalErr
}
@ -670,10 +670,10 @@ func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirec
// 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) {
if errors.Is(err, fs.ErrNotExist) {
return "404 page not found", StatusNotFound
}
if os.IsPermission(err) {
if errors.Is(err, fs.ErrPermission) {
return "403 Forbidden", StatusForbidden
}
// Default:

View file

@ -1270,16 +1270,18 @@ func TestFileServerNotDirError(t *testing.T) {
if err == nil {
t.Fatal("err == nil; want != nil")
}
if !os.IsNotExist(err) {
t.Errorf("err = %v; os.IsNotExist(err) = %v; want true", err, os.IsNotExist(err))
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("err = %v; errors.Is(err, fs.ErrNotExist) = %v; want true", err,
errors.Is(err, fs.ErrNotExist))
}
_, err = dir.Open("/index.html/not-a-dir/not-a-file")
if err == nil {
t.Fatal("err == nil; want != nil")
}
if !os.IsNotExist(err) {
t.Errorf("err = %v; os.IsNotExist(err) = %v; want true", err, os.IsNotExist(err))
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("err = %v; errors.Is(err, fs.ErrNotExist) = %v; want true", err,
errors.Is(err, fs.ErrNotExist))
}
})
}