feat: http handler to create images on disk

This commit is contained in:
2025-02-22 11:56:50 +00:00
commit be0258e195
2 changed files with 66 additions and 0 deletions

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module screenmark/screenmark
go 1.24.0

63
main.go Normal file
View File

@ -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)
}