From dfa06e206df99bb3ec9d7926eca5af1655c6cf1f Mon Sep 17 00:00:00 2001 From: Eldon Stegall Date: Sun, 18 Aug 2024 04:17:00 +0000 Subject: [PATCH] Use embeds for home files in examples Rather than serving up the html files directly from whatever directory the program is run in, embed the files in the binary. --- examples/chat/main.go | 8 +++++++- examples/command/main.go | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/examples/chat/main.go b/examples/chat/main.go index 474709f..e462248 100644 --- a/examples/chat/main.go +++ b/examples/chat/main.go @@ -5,13 +5,19 @@ package main import ( + "bytes" + _ "embed" "flag" "log" "net/http" + "time" ) var addr = flag.String("addr", ":8080", "http service address") +//go:embed home.html +var homeHtml []byte + func serveHome(w http.ResponseWriter, r *http.Request) { log.Println(r.URL) if r.URL.Path != "/" { @@ -22,7 +28,7 @@ func serveHome(w http.ResponseWriter, r *http.Request) { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } - http.ServeFile(w, r, "home.html") + http.ServeContent(w, r, "home.html", time.Now(), bytes.NewReader(homeHtml)) } func main() { diff --git a/examples/command/main.go b/examples/command/main.go index 38d9f6c..6edf949 100644 --- a/examples/command/main.go +++ b/examples/command/main.go @@ -6,6 +6,8 @@ package main import ( "bufio" + "bytes" + _ "embed" "flag" "io" "log" @@ -165,6 +167,9 @@ func serveWs(w http.ResponseWriter, r *http.Request) { } } +//go:embed home.html +var homeHtml []byte + func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found", http.StatusNotFound) @@ -174,7 +179,7 @@ func serveHome(w http.ResponseWriter, r *http.Request) { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } - http.ServeFile(w, r, "home.html") + http.ServeContent(w, r, "home.html", time.Now(), bytes.NewReader(homeHtml)) } func main() {