-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (78 loc) · 2.19 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
package main
import (
"fmt"
"html/template"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
// parse and execute the template
t, _ := template.ParseFiles("templates/index.html")
t.Execute(w, nil)
}
// https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/04.5.html
// https://github.com/astaxie/build-web-application-with-golang/blob/master/en/04.4.md
// http://stackoverflow.com/questions/15202448/go-formfile-for-multiple-files
// upload logic
func uploadHandler(w http.ResponseWriter, r *http.Request) {
// generate semi-random filename
rand.Seed(time.Now().UnixNano())
name := randSeq(10)
r.ParseMultipartForm(32 << 20) // 32MB is the default used by FormFile
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// log some data to console
fmt.Printf("Processing: %v\n", handler.Header)
// create the directory path if needed
os.MkdirAll("./tmp/", 0755)
// save the file
f, err := os.OpenFile("./tmp/"+name, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
// probe file
probedata := probe(name)
fmt.Fprintf(w, "%v", probedata)
}
func probe(filename string) string {
// convert example.png json:
cmd := exec.Command("convert", "/app/tmp/"+filename, "json:")
//fmt.Println(cmd)
response, err := cmd.CombinedOutput()
if err != nil {
return "ERROR in cmd.CombinedOutput()"
}
// dump contents of command
//fmt.Println(response)
// hopefully return json
return string(response)
}
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", indexHandler)
http.HandleFunc("/upload", uploadHandler)
log.Println("Listening 5000...")
http.ListenAndServe(":5000", nil)
}