-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (54 loc) · 1.63 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
var client *http.Client = http.DefaultClient
func main() {
port := ":8080"
http.HandleFunc("/upload", serveUpload)
log.Printf("Running on port %s\n", port)
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func serveUpload(w http.ResponseWriter, r *http.Request) {
log.Println("File Upload Endpoint Hit")
// Parse our multipart form, 10 << 20 specifies a maximum
// upload of 10 MB files.
r.ParseMultipartForm(10 << 20)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, handler, err := r.FormFile("myFile")
if err != nil {
log.Println("Error Retrieving the File")
log.Println(err)
return
}
defer file.Close()
log.Printf("Uploaded File: %+v\n", handler.Filename)
log.Printf("File Size: %+v\n", handler.Size)
log.Printf("MIME Header: %+v\n", handler.Header)
// Create a temporary file within our temp-images directory that follows
// a particular naming pattern
tempFile, err := ioutil.TempFile("temp-images", "upload-*.png")
if err != nil {
log.Println(err)
}
// read all of the contents of our uploaded file into a
// byte array
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
log.Println(err)
}
// write this byte array to our temporary file
tempFile.Write(fileBytes)
tempFile.Close()
createPostCardResponse := CreatePostCard(r.FormValue("to"), r.FormValue("from"), tempFile.Name())
// return that we have successfully uploaded our file!
fmt.Fprintf(w, createPostCardResponse)
}