-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
72 lines (58 loc) · 1.68 KB
/
response.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
package main
import (
"encoding/json"
"io/fs"
"net/http"
"strings"
"time"
"github.com/gabriel-vasile/mimetype"
)
type errorJson struct {
Message string `json:"message"`
}
type fileCreatedJson struct {
Url string `json:"url"`
Relative string `json:"relative"`
}
type fileDetailsJson struct {
Filename string `json:"filename"`
Size int64 `json:"size"`
ModificationTime string `json:"modification_time"`
Filetype string `json:"filetype"`
}
func jsonErrorResponse(w http.ResponseWriter, message string, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
p := errorJson{Message: message}
json.NewEncoder(w).Encode(p)
}
func jsonFileCreatedResponse(w http.ResponseWriter, url string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
p := fileCreatedJson{url, strings.TrimPrefix(url, getFullHostname())}
json.NewEncoder(w).Encode(p)
}
func jsonFileNotFound(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
p := errorJson{Message: "Given file doesn't exist"}
json.NewEncoder(w).Encode(p)
}
func jsonFileDetails(w http.ResponseWriter, path string, fileInfo fs.FileInfo) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var filetype string
mtype, err := mimetype.DetectFile(path)
if err != nil {
filetype = "Unknown"
} else {
filetype = mtype.String()
}
p := fileDetailsJson{
Filename: fileInfo.Name(),
Size: fileInfo.Size(),
ModificationTime: fileInfo.ModTime().UTC().Format(time.RFC3339),
Filetype: filetype,
}
json.NewEncoder(w).Encode(p)
}