-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
165 lines (141 loc) · 4.64 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/joho/godotenv"
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
)
var HOST string
var PORT int64
var UPLOADS_DIR string
var API_KEY string
func init() {
err := godotenv.Load()
if err != nil {
log.Fatalf("[ERROR] Couldn't load the .env file: %s", err)
}
HOST = os.Getenv("HOST")
if HOST == "" {
log.Println("[WARNING] The environment variable 'HOST' is not set - The full URL of uploaded response will be invalid")
}
portStr := os.Getenv("PORT")
if portStr == "" {
log.Println("[WARNING] The environment variable 'PORT' is not set - The full URL of uploaded response will be invalid")
}
PORT, err = strconv.ParseInt(portStr, 10, 32)
if portStr == "" || err != nil {
log.Println("[WARNING] The environment variable 'PORT' is not a number")
}
UPLOADS_DIR = os.Getenv("UPLOADS_DIR")
if UPLOADS_DIR == "" {
log.Fatal("[ERROR] The environment variable 'UPLOADS_DIR' is not set")
}
API_KEY = os.Getenv("API_KEY")
if API_KEY == "" {
log.Fatal("[ERROR] The environment variable 'API_KEY' is not set")
}
}
func main() {
router := httprouter.New()
router.GET("/*filepath", serveFile())
router.POST("/*filepath", uploadFile())
handler := cors.Default().Handler(router)
log.Printf("Listening on port %d\n", PORT)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", PORT), handler))
}
func serveFile() httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
fileReq := p.ByName("filepath")
// disable / or /assets/childdirective/../
if fileReq == "/" || (len(fileReq) > 1 && fileReq[len(fileReq)-1:] == "/") {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 page not found")
return
}
switch viewMode := r.URL.Query().Get("view"); strings.ToLower(viewMode) {
case "detail":
fileLocationInDisk := filepath.Join(UPLOADS_DIR, fileReq)
fileInfo, err := os.Stat(fileLocationInDisk)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
jsonFileNotFound(w)
return
} else {
jsonErrorResponse(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
return
}
}
jsonFileDetails(w, fileLocationInDisk, fileInfo)
return
default:
r.URL.Path = fileReq
fileServer := http.FileServer(http.Dir(UPLOADS_DIR))
fileServer.ServeHTTP(w, r)
}
}
}
func uploadFile() httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
headerAPIKey := r.Header.Get("x-spupload-api-key")
if headerAPIKey != API_KEY {
jsonErrorResponse(w, fmt.Sprintf("Invalid 'x-spupload-api-key' header value"), http.StatusBadRequest)
return
}
customFilename := r.PostFormValue("filename")
replaceFile := r.PostFormValue("replace") == "true"
disableFileOptimization := r.PostFormValue("disable-file-optimization") == "true"
fileReq := p.ByName("filepath")
uploadLocation := filepath.Join(UPLOADS_DIR, fileReq)
fileUploaded, fileUploadedHeader, err := r.FormFile("file")
if err != nil {
jsonErrorResponse(w, fmt.Sprintf("Couldn't parse file from the request: %s", err), http.StatusInternalServerError)
return
}
defer fileUploaded.Close()
var outputFilepath string
if customFilename != "" {
fileExtension := filepath.Ext(fileUploadedHeader.Filename)
outputFilepath = filepath.Join(uploadLocation, fmt.Sprintf("%s%s", customFilename, fileExtension))
} else {
outputFilepath = filepath.Join(uploadLocation, fileUploadedHeader.Filename)
}
outputFileDir := filepath.Dir(outputFilepath)
err = os.MkdirAll(outputFileDir, os.ModePerm)
if err != nil {
jsonErrorResponse(w, fmt.Sprintf("Couldn't create output directory: %s", err), http.StatusInternalServerError)
return
}
uploadedBuffer := bytes.NewBuffer(nil)
if _, err := io.Copy(uploadedBuffer, fileUploaded); err != nil {
jsonErrorResponse(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
return
}
if !disableFileOptimization {
optimizeFile(&outputFilepath, uploadedBuffer)
}
if !replaceFile {
outputFilepath = getProperAvailableFilepath(outputFilepath)
}
fileOut, err := os.OpenFile(outputFilepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
jsonErrorResponse(w, fmt.Sprintf("Couldn't create output file: %s", err), http.StatusInternalServerError)
return
}
io.Copy(fileOut, uploadedBuffer)
downloadUrl, err := filepathToDownloadUrl(outputFilepath)
if err != nil {
jsonErrorResponse(w, fmt.Sprintf("Couldn't generate download link: %s", err), http.StatusInternalServerError)
return
}
jsonFileCreatedResponse(w, downloadUrl)
}
}