Last active
March 17, 2021 21:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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