

[Golang] File Server With Custom 404 Not Found
source link: http://siongui.github.io/2017/03/19/go-file-server-with-custom-404-not-found/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Golang] File Server With Custom 404 Not Found
March 19, 2017
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
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:
[3]func StripPrefix - net/http - The Go Programming Language
[4]file server with custom 404 · siongui/pali@e872a78 · GitHub
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK