aboutsummaryrefslogtreecommitdiff
path: root/internal/image/handler.go
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--internal/image/handler.go71
1 files changed, 71 insertions, 0 deletions
diff --git a/internal/image/handler.go b/internal/image/handler.go
new file mode 100644
index 0000000..8988a58
--- /dev/null
+++ b/internal/image/handler.go
@@ -0,0 +1,71 @@
+package image
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+)
+
+var fileTypes = map[string]string{
+ "image/jpeg": "jpg",
+ "image/png": "png",
+}
+
+// Handler image handler interface
+type Handler interface {
+ GetImage(w http.ResponseWriter, r *http.Request)
+ PostImage(w http.ResponseWriter, r *http.Request)
+}
+
+// NewHandler create image handler struct
+func NewHandler(service Servicer) Handler {
+ return &imageHandler{service}
+}
+
+type imageHandler struct {
+ service Servicer
+}
+
+func (h *imageHandler) GetImage(w http.ResponseWriter, r *http.Request) {
+ log.Print("serving image")
+ http.ServeFile(w, r, "foo.jpg")
+}
+
+// PostImage handler for creating an image post
+func (h *imageHandler) PostImage(w http.ResponseWriter, r *http.Request) {
+ // max size
+ r.ParseMultipartForm(10 << 20)
+ file, handler, err := r.FormFile("file")
+ if err != nil {
+ log.Printf("%s", err)
+ }
+ defer file.Close()
+ fileBytes, err := ioutil.ReadAll(file)
+ if err != nil {
+ log.Printf("%s", err)
+ log.Printf("unsupported filetype")
+ w.WriteHeader(400)
+ w.Write([]byte("Incorrect Content Type"))
+ return
+ }
+ fileType := http.DetectContentType(fileBytes)
+ if fileType != handler.Header.Get("Content-Type") {
+ log.Printf("file type and content type do not match")
+ w.WriteHeader(400)
+ w.Write([]byte("Incorrect Content Type"))
+ return
+ }
+ extension, exists := fileTypes[fileType]
+ if !exists {
+ log.Printf("unsupported filetype")
+ w.WriteHeader(400)
+ w.Write([]byte("Incorrect Content Type"))
+ return
+ }
+ fileID, err := h.service.NewID()
+ fileName := fmt.Sprintf("%s.%s", fileID, extension)
+ h.service.AddFile(fileName, fileBytes)
+ w.WriteHeader(201)
+ w.Write([]byte("ok"))
+}