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.
This commit is contained in:
Eldon Stegall 2024-08-18 04:17:00 +00:00
parent 5e00238113
commit dfa06e206d
2 changed files with 13 additions and 2 deletions

View File

@ -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() {

View File

@ -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() {