-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathmain.go
108 lines (96 loc) · 2.89 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
package main
import (
"crypto/rand"
"fmt"
"html/template"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"path/filepath"
)
const maxUploadSize = 2 * 1024 * 1024 // 2 mb
var uploadPath = os.TempDir()
func main() {
http.HandleFunc("/upload", uploadFileHandler())
fs := http.FileServer(http.Dir(uploadPath))
http.Handle("/files/", http.StripPrefix("/files", fs))
log.Print("Server started on localhost:8080, use /upload for uploading files and /files/{fileName} for downloading")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func uploadFileHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("upload.gtpl")
t.Execute(w, nil)
return
}
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
fmt.Printf("Could not parse multipart form: %v\n", err)
renderError(w, "CANT_PARSE_FORM", http.StatusInternalServerError)
return
}
// parse and validate file and post parameters
file, fileHeader, err := r.FormFile("uploadFile")
if err != nil {
renderError(w, "INVALID_FILE", http.StatusBadRequest)
return
}
defer file.Close()
// Get and print out file size
fileSize := fileHeader.Size
fmt.Printf("File size (bytes): %v\n", fileSize)
// validate file size
if fileSize > maxUploadSize {
renderError(w, "FILE_TOO_BIG", http.StatusBadRequest)
return
}
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
renderError(w, "INVALID_FILE", http.StatusBadRequest)
return
}
// check file type, detectcontenttype only needs the first 512 bytes
detectedFileType := http.DetectContentType(fileBytes)
switch detectedFileType {
case "image/jpeg", "image/jpg":
case "image/gif", "image/png":
case "application/pdf":
break
default:
renderError(w, "INVALID_FILE_TYPE", http.StatusBadRequest)
return
}
fileName := randToken(12)
fileEndings, err := mime.ExtensionsByType(detectedFileType)
if err != nil {
renderError(w, "CANT_READ_FILE_TYPE", http.StatusInternalServerError)
return
}
newFileName := fileName + fileEndings[0]
newPath := filepath.Join(uploadPath, newFileName)
fmt.Printf("FileType: %s, File: %s\n", detectedFileType, newPath)
// write file
newFile, err := os.Create(newPath)
if err != nil {
renderError(w, "CANT_WRITE_FILE", http.StatusInternalServerError)
return
}
defer newFile.Close() // idempotent, okay to call twice
if _, err := newFile.Write(fileBytes); err != nil || newFile.Close() != nil {
renderError(w, "CANT_WRITE_FILE", http.StatusInternalServerError)
return
}
w.Write([]byte(fmt.Sprintf("SUCCESS - use /files/%v to access the file", newFileName)))
})
}
func renderError(w http.ResponseWriter, message string, statusCode int) {
w.WriteHeader(statusCode)
w.Write([]byte(message))
}
func randToken(len int) string {
b := make([]byte, len)
rand.Read(b)
return fmt.Sprintf("%x", b)
}