From c3585f37eba1e57ee01b4ccc26326bb1afa77bc9 Mon Sep 17 00:00:00 2001 From: raul Date: Wed, 1 May 2024 09:11:25 +0200 Subject: [PATCH] Add embedding files to binary Now this app is truly portable! You don't even need the assets folder when using a compiled binary, as the HTML and CSS are now embedded to the file itself --- main.go | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/main.go b/main.go index f135922..7c2cce8 100644 --- a/main.go +++ b/main.go @@ -1,29 +1,20 @@ package main import ( + "embed" "fmt" "io" + "io/fs" "log" "net/http" "os" ) -// func getRoot(w http.ResponseWriter, r *http.Request) { -// fmt.Printf("Received connection\n") -// file, err := os.Open("./index.html") -// if err != nil { -// log.Printf("Error happened opening index.html: %v\n", err) -// } -// defer file.Close() -// data, err := io.ReadAll(file) -// if err != nil { -// log.Printf("Error happened reading data: %v\n", err) -// } -// fmt.Fprint(w, string(data)) -// } +//go:embed assets +var assetsFolder embed.FS func uploadFile(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, "You have uploaded something") + fmt.Fprintln(w, "Successful upload!") file, header, err := r.FormFile("file") @@ -31,6 +22,8 @@ func uploadFile(w http.ResponseWriter, r *http.Request) { log.Printf("Error happened receiving file: %v\n", err) } + defer file.Close() + _, err = os.Stat("./temp/") if os.IsNotExist(err) { os.Mkdir("./temp/", 0700) @@ -40,19 +33,23 @@ func uploadFile(w http.ResponseWriter, r *http.Request) { if err != nil { log.Printf("Error happened opening file: %v\n", err) } + log.Printf("[%v] Received file \"%v\" from %v\n", r.RemoteAddr, header.Filename, r.UserAgent()) io.Copy(f, file) - - defer file.Close() } func main() { - http.Handle("/", http.FileServer(http.Dir("./assets"))) + serverRoot, err := fs.Sub(assetsFolder, "assets") + if err != nil { + log.Fatalf("Error occurred setting HTML root: %v\n", err) + } + + http.Handle("/", http.FileServer(http.FS(serverRoot))) http.HandleFunc("/api/upload", uploadFile) fmt.Println("Listening on port 8080...") - err := http.ListenAndServe(":8080", nil) + err = http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) }