This repository has been archived by the owner on Nov 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
fineuploader-go-server.go
190 lines (168 loc) · 5.06 KB
/
fineuploader-go-server.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// An upload server for fineuploader.com javascript upload library
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
)
var port = flag.Int("p", 8080, "Port number to listen to, defaults to 8080")
var uploadDir = flag.String("d", "uploads", "Upload directory, defaults to 'uploads'")
// Request parameters
const (
paramUuid = "qquuid" // uuid
paramFile = "qqfile" // file name
)
// Chunked request parameters
const (
paramPartIndex = "qqpartindex" // part index
paramPartBytesOffset = "qqpartbyteoffset" // part byte offset
paramTotalFileSize = "qqtotalfilesize" // total file size
paramTotalParts = "qqtotalparts" // total parts
paramFileName = "qqfilename" // file name for chunked requests
paramChunkSize = "qqchunksize" // size of the chunks
)
type UploadResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
PreventRetry bool `json:"preventRetry"`
}
func main() {
flag.Parse()
hostPort := fmt.Sprintf("0.0.0.0:%d", *port)
log.Printf("Initiating server listening at [%s]", hostPort)
log.Printf("Base upload directory set to [%s]", *uploadDir)
http.HandleFunc("/upload", UploadHandler)
http.HandleFunc("/chunksdone", ChunksDoneHandler)
http.Handle("/upload/", http.StripPrefix("/upload/", http.HandlerFunc(UploadHandler)))
log.Fatal(http.ListenAndServe(hostPort, nil))
}
func UploadHandler(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodPost:
upload(w, req)
return
case http.MethodDelete:
delete(w, req)
return
}
errorMsg := fmt.Sprintf("Method [%s] is not supported:", req.Method)
http.Error(w, errorMsg, http.StatusMethodNotAllowed)
}
func upload(w http.ResponseWriter, req *http.Request) {
uuid := req.FormValue(paramUuid)
if len(uuid) == 0 {
log.Printf("No uuid received, invalid upload request")
http.Error(w, "No uuid received", http.StatusBadRequest)
return
}
log.Printf("Starting upload handling of request with uuid of [%s]\n", uuid)
file, headers, err := req.FormFile(paramFile)
if err != nil {
writeUploadResponse(w, err)
return
}
fileDir := fmt.Sprintf("%s/%s", *uploadDir, uuid)
if err := os.MkdirAll(fileDir, 0777); err != nil {
writeUploadResponse(w, err)
return
}
var filename string
partIndex := req.FormValue(paramPartIndex)
if len(partIndex) == 0 {
filename = fmt.Sprintf("%s/%s", fileDir, headers.Filename)
} else {
filename = fmt.Sprintf("%s/%s_%05s", fileDir, uuid, partIndex)
}
outfile, err := os.Create(filename)
if err != nil {
writeUploadResponse(w, err)
return
}
defer outfile.Close()
_, err = io.Copy(outfile, file)
if err != nil {
writeUploadResponse(w, err)
return
}
writeUploadResponse(w, nil)
}
func delete(w http.ResponseWriter, req *http.Request) {
log.Printf("Delete request received for uuid [%s]", req.URL.Path)
err := os.RemoveAll(*uploadDir + "/" + req.URL.Path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
}
func ChunksDoneHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
errorMsg := fmt.Sprintf("Method [%s] is not supported", req.Method)
http.Error(w, errorMsg, http.StatusMethodNotAllowed)
}
uuid := req.FormValue(paramUuid)
filename := req.FormValue(paramFileName)
totalFileSize, err := strconv.Atoi(req.FormValue(paramTotalFileSize))
if err != nil {
writeHttpResponse(w, http.StatusInternalServerError, err)
return
}
totalParts, err := strconv.Atoi(req.FormValue(paramTotalParts))
if err != nil {
writeHttpResponse(w, http.StatusInternalServerError, err)
return
}
finalFilename := fmt.Sprintf("%s/%s/%s", *uploadDir, uuid, filename)
f, err := os.Create(finalFilename)
if err != nil {
writeHttpResponse(w, http.StatusInternalServerError, err)
return
}
defer f.Close()
var totalWritten int64
for i := 0; i < totalParts; i++ {
part := fmt.Sprintf("%[1]s/%[2]s/%[2]s_%05[3]d", *uploadDir, uuid, i)
partFile, err := os.Open(part)
if err != nil {
writeHttpResponse(w, http.StatusInternalServerError, err)
return
}
written, err := io.Copy(f, partFile)
if err != nil {
writeHttpResponse(w, http.StatusInternalServerError, err)
return
}
partFile.Close()
totalWritten += written
if err := os.Remove(part); err != nil {
log.Printf("Error: %v", err)
}
}
if totalWritten != int64(totalFileSize) {
errorMsg := fmt.Sprintf("Total file size mistmatch, expected %d bytes but actual is %d", totalFileSize, totalWritten)
http.Error(w, errorMsg, http.StatusMethodNotAllowed)
}
}
func writeHttpResponse(w http.ResponseWriter, httpCode int, err error) {
w.WriteHeader(httpCode)
if err != nil {
log.Printf("An error happened: %v", err)
w.Write([]byte(err.Error()))
}
}
func writeUploadResponse(w http.ResponseWriter, err error) {
uploadResponse := new(UploadResponse)
if err != nil {
uploadResponse.Error = err.Error()
} else {
uploadResponse.Success = true
}
w.Header().Set("Content-Type", "text/plain")
json.NewEncoder(w).Encode(uploadResponse)
}