Skip to content

Instantly share code, notes, and snippets.

@morgangallant
Last active March 17, 2021 21:08
Show Gist options
  • Save morgangallant/9b2d1d8bbb4620b775bf12cba6f58761 to your computer and use it in GitHub Desktop.
Save morgangallant/9b2d1d8bbb4620b775bf12cba6f58761 to your computer and use it in GitHub Desktop.
An easy way to serve static websites via HTTP with new Go io/fs package.
package main
import (
"embed"
"errors"
"io/fs"
"log"
"net/http"
"strings"
)
//go:embed website
var static embed.FS
type htmlStripperFS struct{ underlying fs.FS }
func (hs *htmlStripperFS) Open(name string) (fs.File, error) {
f, err := hs.underlying.Open(name)
if err != nil && errors.Is(err, fs.ErrNotExist) && !strings.HasSuffix(name, ".html") {
f, err = hs.underlying.Open(name + ".html")
}
return f, err
}
func run() error {
// Serve static files from the /website embedded directory.
ws, err := fs.Sub(fs.FS(static), "website")
if err != nil {
return err
}
http.Handle("/", http.FileServer(http.FS(&htmlStripperFS{ws})))
return http.ListenAndServe(":8080", nil)
}
func main() {
if err := run(); err != nil {
log.Fatalf("error in run(): %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment