[Golang] File Server With Custom 404 Not Found


Implementation of static file server with custom HTTP 404 Not Found handler via Go standard net/http package.

The built-in FileServer method in standard net/http package can serve staic files in the file syatem, but does not allow custom 404 Not Found handler, so I implement my own FileServer method with custom 404 handler.

The idea of implementation of FileServer with custom 404 handler comes from the implementation of StripPrefix method in the same net/http package. You can read the code of StripPrefix method for more details.

The key idea of my implementation:

  • Accept the same parameters (FileSystem) as FileServer method, which is return value of http.Dir in normal case.
  • Use the FileSystem.Open and os.IsNotExist methods to check if the file exists. If not, call custom 404 handler. Otherwise serve the file with normal FileServer handler.

Source Code:

server.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
	"fmt"
	"net/http"
	"os"
	"path"
)

func NotFound(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "my 404 page!")
}

func FileServerWithCustom404(fs http.FileSystem) http.Handler {
	fsh := http.FileServer(fs)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := fs.Open(path.Clean(r.URL.Path))
		if os.IsNotExist(err) {
			NotFound(w, r)
			return
		}
		fsh.ServeHTTP(w, r)
	})
}

func main() {
	http.ListenAndServe(":8080", FileServerWithCustom404(http.Dir("/usr/share/doc")))
}

Not sure whether this implementation is robust or not, but it works well in my application.


Tested on:

  • Ubuntu Linux 16.10
  • Go 1.8

References:

[1]
[2]
[3]func StripPrefix - net/http - The Go Programming Language
[4]file server with custom 404 · siongui/pali@e872a78 · GitHub
[5]How to serve static files with custom NotFound handler : golang How to serve static files with custom NotFound handler - Blog from kefaise.com