uploader/main.go

57 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-04-30 10:53:18 +02:00
package main
import (
"embed"
2024-04-30 10:53:18 +02:00
"fmt"
"io"
"io/fs"
2024-04-30 10:53:18 +02:00
"log"
"net/http"
"os"
)
//go:embed assets
var assetsFolder embed.FS
2024-04-30 10:53:18 +02:00
func uploadFile(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Successful upload!")
2024-04-30 11:25:36 +02:00
file, header, err := r.FormFile("file")
if err != nil {
log.Printf("Error happened receiving file: %v\n", err)
}
2024-04-30 12:11:26 +02:00
defer file.Close()
_, err = os.Stat("./temp/")
if os.IsNotExist(err) {
os.Mkdir("./temp/", 0700)
}
2024-04-30 11:25:36 +02:00
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)
}
2024-04-30 12:11:26 +02:00
log.Printf("[%v] Received file \"%v\" from %v\n", r.RemoteAddr, header.Filename, r.UserAgent())
2024-04-30 11:25:36 +02:00
io.Copy(f, file)
2024-04-30 10:53:18 +02:00
}
func main() {
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)))
2024-04-30 10:53:18 +02:00
http.HandleFunc("/api/upload", uploadFile)
2024-04-30 11:25:36 +02:00
fmt.Println("Listening on port 8080...")
err = http.ListenAndServe(":8080", nil)
2024-04-30 10:53:18 +02:00
if err != nil {
log.Fatal(err)
}
}