From c9c8a03f8f5c6cc4fea5bf0ff3d03f40b0f85cb5 Mon Sep 17 00:00:00 2001 From: raul Date: Tue, 30 Apr 2024 12:11:26 +0200 Subject: [PATCH] Improve file serving using built-ins --- main.go | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/main.go b/main.go index b2e15fb..beade32 100644 --- a/main.go +++ b/main.go @@ -8,22 +8,21 @@ import ( "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)) -} +// 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)) +// } func uploadFile(w http.ResponseWriter, r *http.Request) { - fmt.Printf("Received upload!\n") fmt.Fprintln(w, "You have uploaded something") file, header, err := r.FormFile("file") @@ -31,18 +30,19 @@ func uploadFile(w http.ResponseWriter, r *http.Request) { if err != nil { log.Printf("Error happened receiving file: %v\n", err) } - fmt.Fprintf(w, "%v", header.Header) + f, err := os.OpenFile("./temp/"+header.Filename, os.O_WRONLY|os.O_CREATE, 0660) 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.HandleFunc("/", getRoot) + http.Handle("/", http.FileServer(http.Dir("./assets"))) http.HandleFunc("/api/upload", uploadFile) fmt.Println("Listening on port 8080...")