Skip to content

Instantly share code, notes, and snippets.

@ptdorf
Forked from bmcculley/README.md
Created March 26, 2024 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptdorf/d22de921993d548264a982d7ab404fc5 to your computer and use it in GitHub Desktop.
Save ptdorf/d22de921993d548264a982d7ab404fc5 to your computer and use it in GitHub Desktop.
A Go embed example of serving static files at the root URL path.
package main
import (
"embed"
"fmt"
"io/fs"
"log"
"net/http"
"os"
)
//go:embed public
var staticFiles embed.FS
func main() {
var staticFS = fs.FS(staticFiles)
htmlContent, err := fs.Sub(staticFS, "public")
if err != nil {
log.Fatal(err)
}
fs := http.FileServer(http.FS(htmlContent))
// Serve static files
http.Handle("/", fs)
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Printf("Listening on :%s...\n", port)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
if err != nil {
log.Fatal(err)
}
}
<!doctype html>
<!-- public/index.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Go embed example</title>
<meta name="description" content="Go embed example">
<meta name="author" content="bmcculley">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<p>A Go <a href="https://golang.org/pkg/embed/">embed</a> example of serving static files at the root URL path.</p>
</body>
</html>
package main
import (
"embed"
"fmt"
"log"
"net/http"
"os"
"strings"
)
//go:embed public
var staticFiles embed.FS
var staticDir = "public"
func rootPath(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// add header(s)
w.Header().Set("Cache-Control", "no-cache")
if r.URL.Path == "/" {
r.URL.Path = fmt.Sprintf("/%s/", staticDir)
} else {
b := strings.Split(r.URL.Path, "/")[0]
if b != staticDir {
r.URL.Path = fmt.Sprintf("/%s%s", staticDir, r.URL.Path)
}
}
h.ServeHTTP(w, r)
})
}
func main() {
var staticFS = http.FS(staticFiles)
fs := rootPath(http.FileServer(staticFS))
// Serve static files
http.Handle("/", fs)
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Printf("Listening on :%s...\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
if err != nil {
log.Fatal(err)
}
}
/* public/css/style.css */
body {
margin: 20px;
font-family: sans-serif;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
background-color: #fff;
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment