-
Notifications
You must be signed in to change notification settings - Fork 28
/
upload.go
64 lines (54 loc) · 1.56 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package cdn
import (
"fmt"
"io/ioutil"
"net/http"
"realm.pub/tavern/internal/ent"
"realm.pub/tavern/internal/ent/file"
"realm.pub/tavern/internal/errors"
)
// DefaultMaxUploadSize defines the maximum number of bytes an uploaded file can be.
const DefaultMaxUploadSize = 10 << 20
// NewUploadHandler returns an HTTP handler responsible for uploading a file to the CDN.
func NewUploadHandler(graph *ent.Client) http.Handler {
return errors.WrapHandler(func(w http.ResponseWriter, req *http.Request) error {
ctx := req.Context()
// Get the File name
if err := req.ParseMultipartForm(DefaultMaxUploadSize); err != nil {
return err
}
fileName := req.PostFormValue("fileName")
if fileName == "" {
return ErrInvalidFileName
}
// Get the File content
f, _, err := req.FormFile("fileContent")
if err != nil {
return fmt.Errorf("%w: %v", ErrInvalidFileContent, err)
}
defer f.Close()
fileContent, err := ioutil.ReadAll(f)
if err != nil {
return fmt.Errorf("%w: %v", ErrInvalidFileContent, err)
}
// Check if it has already been uploaded
fileQuery := graph.File.Query().Where(file.Name(fileName))
exists := fileQuery.Clone().ExistX(ctx)
// Create or Update the file
var fileID int
if exists {
fileID = fileQuery.OnlyIDX(ctx)
graph.File.UpdateOneID(fileID).
SetContent(fileContent).
SaveX(ctx)
} else {
fileID = graph.File.Create().
SetName(fileName).
SetContent(fileContent).
SaveX(ctx).ID
}
// Respond with JSON of the file ID
fmt.Fprintf(w, `{"data":{"file":{"id":%d}}}`, fileID)
return nil
})
}