-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
207 lines (175 loc) · 4.65 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"cloud.google.com/go/storage"
"github.com/gabriel-vasile/mimetype"
"github.com/lithammer/shortuuid"
"google.golang.org/appengine"
)
var tmpHTMLPage []byte
type upfile struct {
name string
origName string
ext string
content []byte
}
var (
storageClient *storage.Client
// Set this in app.yaml when running in production.
bucketName = os.Getenv("GCLOUD_STORAGE_BUCKET")
)
func (u *upfile) URL(r *http.Request) string {
return fmt.Sprintf("https://%s/b/%s%s", r.Host, u.name, u.ext)
}
func (u *upfile) FileName() string {
return fmt.Sprintf("%s%s", u.name, u.ext)
}
func main() {
var err error
tmpHTMLPage, err = ioutil.ReadFile("s/index.html")
if err != nil {
log.Println("Template file couldn't found")
}
http.HandleFunc("/", indexHandler)
http.HandleFunc("/b/", binHandler)
http.HandleFunc("/upload", uploadHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// They don't have to post only /upload path.
if r.Method == "POST" {
uploadHandler(w, r)
return
}
htmlPage := strings.ReplaceAll(string(tmpHTMLPage), "{{Host}}", r.Host)
fmt.Fprint(w, htmlPage)
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
// Only accept POST Request
if r.Method == "GET" {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
formfile, fileHeader, err := r.FormFile("file")
if err != nil {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
defer formfile.Close()
ufile := upfile{}
ufile.name = shortuuid.New()
ufile.content, err = ioutil.ReadAll(formfile)
if fileHeader.Filename == "-" {
ufile.origName = ufile.name
} else {
ufile.origName = fileHeader.Filename
}
if err != nil {
fmt.Fprint(w, err)
return
}
ufile.ext = mimetype.Detect(ufile.content).Extension()
if ufile.ext == "" {
ufile.ext = "."
if strings.Contains(ufile.origName, ".") {
s := strings.Split(ufile.origName, ".")
ufile.ext += s[len(s)-1]
} else {
ufile.ext += "up10"
}
}
switch ufile.ext {
case "exe", "jar", "deb", "xlf": // We don't want to allow this ext
fmt.Fprint(w, fmt.Sprintf("Please contact us for %s", ufile.ext))
default:
if err := writeToCloudStorage(w, r, &ufile); err != nil {
fmt.Fprint(w, err)
return
}
fmt.Fprint(w, ufile.URL(r), "\n")
}
}
func binHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path[0:3] != "/b/" {
http.NotFound(w, r)
return
}
// Only accept GET Request
if r.Method == "POST" {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
fileName := strings.Split(r.URL.Path, "/")[2]
readFromCloudStorage(r, w, fileName)
}
func writeToCloudStorage(w http.ResponseWriter, r *http.Request, ufile *upfile) error {
//log.Println("Creating Background")
//ctx := context.Background()
ctx := appengine.NewContext(r)
client, err := storage.NewClient(ctx)
if err != nil {
log.Printf("Failed to Get Default GCS bucket name: %v", ctx)
return err
}
defer client.Close()
bucket := client.Bucket(bucketName)
wc := bucket.Object(ufile.FileName()).NewWriter(ctx)
wc.ContentDisposition = ufile.origName // + "." + ufile.ext not sure here
size, err := wc.Write(ufile.content)
if err != nil {
log.Println(ctx, "createFile: unable to write bucket %q, file: %s Size:%d, %v", bucket, ufile.FileName(), size, err)
return err
}
if err := wc.Close(); err != nil {
log.Println(ctx, "createFile: unable to close bucket %q, file %q: %v", bucket, ufile.FileName(), err)
return err
}
return nil
}
func readFromCloudStorage(r *http.Request, w http.ResponseWriter, fileName string) error {
ctx := appengine.NewContext(r)
client, _ := storage.NewClient(ctx)
defer client.Close()
bucket := client.Bucket(bucketName)
bucketObject := bucket.Object(fileName)
rc, err := bucketObject.NewReader(ctx)
if err != nil {
log.Println(err)
}
defer rc.Close()
slurp, err := ioutil.ReadAll(rc)
if err != nil {
fmt.Fprint(w, err)
}
ext := mimetype.Detect(slurp)
// Grab ContentDisposition
o, _ := bucketObject.Attrs(ctx)
CD := o.ContentDisposition
// It can be shortuuid but nothing wrong about it
w.Header().Add("Content-Disposition", "filename=\""+string(CD)+"\"")
switch ext.Extension() {
case ".html", ".py", ".js", ".wasm":
w.Header().Add("Content-Type", "text/plain")
default:
w.Header().Add("Content-Type", ext.String())
}
fmt.Fprintf(w, "%s", slurp)
return nil
}