-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
167 lines (142 loc) · 4.08 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
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
package main
import (
"context"
"encoding/json"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/jonwho/bootleg-fs/lrucache"
)
// 1 MB
const maxMemory = 1 * 1024 * 1024
var cache *lrucache.LRUCache
func main() {
srv := &http.Server{
Addr: "0.0.0.0:8080",
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
}
cache = lrucache.New(3)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", handleIndex)
http.HandleFunc("/ping", handlePing)
http.HandleFunc("/upload", handleUpload)
http.HandleFunc("/download", handleDownload)
// start server without blocking
go func() {
log.Fatal(srv.ListenAndServe())
}()
log.Println("Server running on port 8080. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
// Block until signal received
<-sc
// Create a deadline to wait for
gracefulTimeout := time.Second * 7
ctx, cancel := context.WithTimeout(context.Background(), gracefulTimeout)
defer cancel()
// Doesn't block if srv has no connections
srv.Shutdown(ctx)
log.Println("Shutting down server...")
os.Exit(0)
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("templates/layout.html", "templates/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
t.ExecuteTemplate(w, "layout", "")
}
func handlePing(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong!\n"))
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
w.Header().Set("Content-Type", "application/json")
// this totally doesn't work lol
if err := r.ParseMultipartForm(maxMemory); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{ "error": "file size too large" }`))
return
}
file, handler, err := r.FormFile("file")
if err != nil {
log.Println("Error retrieving file from form-data")
log.Println(err)
w.WriteHeader(http.StatusBadRequest) // find better status
w.Write([]byte(`{ "error": "file lost" }`))
return
}
defer file.Close()
log.Printf("Uploaded File: %+v\n", handler.Filename)
log.Printf("Uploaded File Size: %+v\n", handler.Size)
log.Printf("MIME Header: %+v\n", handler.Header)
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
w.WriteHeader(http.StatusBadRequest) // find better status
w.Write([]byte(`{ "error": "file lost" }`))
return
}
// cache it
cache.Set(handler.Filename, fileBytes)
jsonResponse, err := json.Marshal(struct {
Data []byte `json:"data"`
}{Data: fileBytes})
if err != nil {
w.WriteHeader(http.StatusBadRequest) // find better status
w.Write([]byte(`{ "error": "json failure" }`))
return
}
w.WriteHeader(http.StatusCreated)
w.Write(jsonResponse)
} else {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("request not found"))
return
}
}
func handleDownload(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", "application/json")
keys, ok := r.URL.Query()["key"]
if !ok || len(keys) < 1 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{ "error": "key is missing" }`))
return
}
key := keys[0]
data := cache.Get(key)
if data == nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{ "error": "no file found for key" }`))
return
}
jsonResponse, err := json.Marshal(struct {
Data []byte `json:"data"`
}{Data: data})
if err != nil {
w.WriteHeader(http.StatusBadRequest) // find better status
w.Write([]byte(`{ "error": "json failure" }`))
return
}
w.WriteHeader(http.StatusOK)
w.Write(jsonResponse)
} else {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("request not found"))
}
}
func renderTemplate(w http.ResponseWriter, tmpl string) {
t, err := template.ParseFiles("templates/" + tmpl + ".html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
t.Execute(w, nil)
}