-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (53 loc) · 1.21 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
package main
import (
"bytes"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"path/filepath"
"time"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
func RandomString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Int63()%int64(len(letters))]
}
return string(b)
}
func upload(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
return
}
key := r.Header.Get("X-Key")
if key != "shh!" {
return
}
start := time.Now()
file, header, err := r.FormFile("file")
if err != nil {
return
}
buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, file); err != nil {
return
}
fileName := RandomString(6)
fileExt := filepath.Ext(filepath.Clean(header.Filename))[1:]
out, err := os.Create(fmt.Sprintf("./tmp/%s.%s", fileName, fileExt))
if err != nil {
return
}
out.Write(buf.Bytes())
out.Close()
log.Printf("%s uploaded %s.%s in %s", r.RemoteAddr, fileName, fileExt, time.Since(start))
fmt.Fprintf(w, "%s/ss/%s.%s", r.Host, fileName, fileExt)
}
func main() {
http.Handle("/ss/", http.StripPrefix("/ss/", http.FileServer(http.Dir("./tmp"))))
http.HandleFunc("/upload", upload)
log.Fatal(http.ListenAndServe(":3000", nil))
}