1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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"))
}
|