From be0258e195d24e05f4037a22cc0b4ebcc505a51b Mon Sep 17 00:00:00 2001 From: John Costa Date: Sat, 22 Feb 2025 11:56:50 +0000 Subject: [PATCH] feat: http handler to create images on disk --- go.mod | 3 +++ main.go | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e898e15 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module screenmark/screenmark + +go 1.24.0 diff --git a/main.go b/main.go new file mode 100644 index 0000000..51a2dfc --- /dev/null +++ b/main.go @@ -0,0 +1,63 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "os" +) + +func main() { + mux := http.NewServeMux() + + mux.HandleFunc("OPTIONS /image/{name}", func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Access-Control-Allow-Origin", "*") + w.Header().Add("Access-Control-Allow-Credentials", "*") + w.Header().Add("Access-Control-Allow-Headers", "*") + }) + + mux.HandleFunc("POST /image/{name}", func(w http.ResponseWriter, r *http.Request) { + imageName := r.PathValue("name") + + w.Header().Add("Access-Control-Allow-Origin", "*") + w.Header().Add("Access-Control-Allow-Credentials", "*") + w.Header().Add("Access-Control-Allow-Headers", "*") + + if len(imageName) == 0 { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "You need to provide a name in the path") + return + } + + image, err := io.ReadAll(r.Body) + + if err != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Couldnt read the image from the request body") + return + } + + file, err := os.Create("./db/" + imageName) + defer file.Close() + + if err != nil { + log.Println(err) + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Couldnt create the file") + return + } + + _, err = file.Write(image) + if err != nil { + log.Println(err) + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Couldnt write the image") + return + } + }) + + log.Println("Listening and serving.") + + http.ListenAndServe(":3040", mux) +}