-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
88 lines (71 loc) · 1.89 KB
/
create.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package files
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/alexsuriano/drop-drive/internal/queue"
)
func (h *handler) Create(rw http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
file, fileHeader, err := r.FormFile("file")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
path := fmt.Sprintf("/%s", fileHeader.Filename)
err = h.bucket.Upload(file, path)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
entity, err := New(1, fileHeader.Filename, fileHeader.Header.Get("Content-Type"), path)
if err != nil {
h.bucket.Delete(path)
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
folderID := r.Form.Get("folder_id")
if folderID != "" {
fID, err := strconv.Atoi(folderID)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
entity.FolderID = int64(fID)
}
id, err := Insert(h.db, entity)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
entity.ID = id
dto := queue.QueueDTO{
Filename: fileHeader.Filename,
Path: path,
ID: int(id),
}
msg, err := dto.Marshal()
if err != nil {
//TODO: rollback
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
err = h.queue.Publish(msg)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(entity)
}
func Insert(db *sql.DB, file *File) (int64, error) {
statement := `INSERT INTO "Files" ("folder_id", "owner_id", "name", "type",
"path", "modified_at") VALUES ($1, $2, $3, $4, $5, $6)`
result, err := db.Exec(statement, file.FolderID, file.OwnerID, file.Name,
file.Type, file.Path, file.ModifiedAt)
if err != nil {
return -1, err
}
return result.LastInsertId()
}