/
websrv.go
111 lines (87 loc) · 2.17 KB
/
websrv.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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"text/template"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
func CheckError(err error) {
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
panic(err.Error)
}
}
type filestruct struct {
Name string
Data []byte
}
type templdata struct {
Callback string
Files string
}
// Serves Files from the "upload" folder as JSON array
// via JSONP
func GetFiles(w http.ResponseWriter, r *http.Request) {
files_info, err := ioutil.ReadDir("./upload")
CheckError(err)
files := make([]filestruct, len(files_info))
var data []byte
for i, f := range files_info {
if f.IsDir() {
continue
}
data, err = ioutil.ReadFile("./upload/" + f.Name())
CheckError(err)
files[i] = filestruct{Name: f.Name(), Data: data}
os.Remove("./upload/" + f.Name())
}
tmpl, err := template.ParseFiles("./static/getfiles.jsonp")
CheckError(err)
files_json, err := json.Marshal(files)
CheckError(err)
err = tmpl.Execute(w, templdata{Callback: mux.Vars(r)["callback"], Files: string(files_json)})
CheckError(err)
}
// Serves the file index.html
func Index(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("./static/index.html")
defer file.Close()
CheckError(err)
io.Copy(w, file)
}
func ServeJS(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("./js/" + mux.Vars(r)["js_filename"] + ".js")
defer file.Close()
CheckError(err)
io.Copy(w, file)
}
// Recieves Files via JSON Post upload and saves them in the "download" Folder
func Upload(w http.ResponseWriter, r *http.Request) {
var (
err error
files []filestruct
)
err = json.NewDecoder(r.Body).Decode(&files)
CheckError(err)
for _, f := range files {
err = ioutil.WriteFile("./download/"+f.Name, f.Data, 0666)
CheckError(err)
}
fmt.Fprintf(w, "%s", "Got it!")
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/{js_filename}.js", ServeJS)
mx.HandleFunc("/getfiles/callback={callback}", GetFiles)
mx.HandleFunc("/index", Index)
mx.HandleFunc("/upload", Upload)
n := negroni.Classic()
n.UseHandler(cors.Default().Handler(mx))
n.Run(":" + os.Getenv("PORT"))
}