Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Go File Server With Custom Error Pages

DZone's Guide to

A Go File Server With Custom Error Pages

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}