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
This commit is contained in:
raul 2024-05-01 09:11:25 +02:00
parent 4e412c789b
commit c3585f37eb
1 changed files with 15 additions and 18 deletions

33
main.go
View File

@ -1,29 +1,20 @@
package main package main
import ( import (
"embed"
"fmt" "fmt"
"io" "io"
"io/fs"
"log" "log"
"net/http" "net/http"
"os" "os"
) )
// func getRoot(w http.ResponseWriter, r *http.Request) { //go:embed assets
// fmt.Printf("Received connection\n") var assetsFolder embed.FS
// 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))
// }
func uploadFile(w http.ResponseWriter, r *http.Request) { 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") 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) log.Printf("Error happened receiving file: %v\n", err)
} }
defer file.Close()
_, err = os.Stat("./temp/") _, err = os.Stat("./temp/")
if os.IsNotExist(err) { if os.IsNotExist(err) {
os.Mkdir("./temp/", 0700) os.Mkdir("./temp/", 0700)
@ -40,19 +33,23 @@ func uploadFile(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
log.Printf("Error happened opening file: %v\n", err) log.Printf("Error happened opening file: %v\n", err)
} }
log.Printf("[%v] Received file \"%v\" from %v\n", r.RemoteAddr, header.Filename, r.UserAgent()) log.Printf("[%v] Received file \"%v\" from %v\n", r.RemoteAddr, header.Filename, r.UserAgent())
io.Copy(f, file) io.Copy(f, file)
defer file.Close()
} }
func main() { 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) http.HandleFunc("/api/upload", uploadFile)
fmt.Println("Listening on port 8080...") fmt.Println("Listening on port 8080...")
err := http.ListenAndServe(":8080", nil) err = http.ListenAndServe(":8080", nil)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }