-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.go
49 lines (42 loc) · 1.27 KB
/
upload.go
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
package media
import (
"encoding/json"
"net/http"
"github.com/kara9renai/yokattar-go/pkg/config"
"github.com/kara9renai/yokattar-go/pkg/domain/object"
"github.com/kara9renai/yokattar-go/pkg/server/handler/httperror"
)
// Handle Request for POST `v1/media`
func (h *handler) Upload(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
attachment := new(object.Attachment)
r.Body = http.MaxBytesReader(w, r.Body, config.MaxUploadSize)
// ParseMutipartFormはリクエストボディを`multipart/form-data`として解析する関数
if err := r.ParseMultipartForm(config.MaxUploadSize); err != nil {
httperror.InternalServerError(w, err)
return
}
file, fileHeader, err := r.FormFile("file")
if err != nil {
httperror.BadRequest(w, err)
return
}
defer file.Close()
fileName := attachment.CreateFileName(fileHeader)
err = attachment.CopyFile(file, fileName)
if err != nil {
httperror.InternalServerError(w, err)
return
}
at := h.app.Dao.Attachment() // domain/repositoryの取得
attachment, err = at.Save(ctx, fileName)
if err != nil {
httperror.InternalServerError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(attachment); err != nil {
httperror.InternalServerError(w, err)
return
}
}