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

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}