Over a million developers have joined DZone.

A Go File Server With Custom Error Pages

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

While working on the book Go in Practice I found an annoying little problem in the Go built-in file server. The error pages, such as a 404 Not Found response, had no ability to be customized. What is does send are text, not HTML, with an error message in English.

If you're into web development than customizing these pages is needed. The customizations can be made to make the pages useful, to put hidden gems in them (for example, a video game), or simply to have the design match their site.

To work around this problem I created a file server that can be customized. The error handling in the built-in file server is at a low enough level you can't easily work around it without a new package. This package takes advantage of the Go standard library where ever possible and it works in a similar manner to the built-in file server.

package main

import (
    "fmt"
    "net/http"

    "github.com/Masterminds/go-fileserver"
)

func main() {

    // Specity a NotFoundHandler to use when no file is found.
    fileserver.NotFoundHandler = func(w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        fmt.Fprintln(w, "That page could not be found.")
    }

    // Serve a directory of files.
    dir := http.Dir("./files")
    http.ListenAndServe(":8080", fileserver.FileServer(dir))
}


Note, I did file an issue with the Go project in an attempt to add customizations there. Unfortunately, that issue and work did not move forward.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript ,tips and tricks ,go ,web framework

Published at DZone with permission of Matt Farina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}