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
|
package main
import (
"net/http"
"html/template"
"log"
"fmt"
"embed"
"io"
"os"
"path"
"path/filepath"
"flag"
"github.com/google/uuid"
)
//go:embed templates
var tmplFS embed.FS
type BoxHandler struct {
dataPath string
token string
}
func serve(w http.ResponseWriter, token string, views ...string) {
t, err := template.New("index.html").ParseFS(tmplFS, views...)
if err != nil {
log.Fatal(err)
}
if err := t.Execute(w, token); err != nil {
log.Fatal(err)
}
}
func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if r.URL.Path == "/" {
serve(w, handler.token, "templates/index.html")
} else {
resourceId := path.Base(r.URL.Path)
f, err := os.Open(filepath.Join(handler.dataPath, resourceId))
if err != nil {
log.Println(err)
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
io.Copy(w, f)
}
return
case http.MethodPost:
token := r.Header.Get("X-Upload-Token")
if token != handler.token {
log.Println("unauthorized")
w.WriteHeader(http.StatusUnauthorized)
return
}
u, err := uuid.NewRandom()
if err != nil {
log.Println(err)
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
filename := filepath.Join(handler.dataPath, u.String())
log.Printf("boxing %s\n", filename)
f, err := os.Create(filename)
if err != nil {
log.Println(err)
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
io.Copy(f, r.Body)
w.Header().Add("X-Resource-ID", filepath.Base(filename))
log.Printf("boxed %s\n", filename)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
host := flag.String("n", "", "The hostname to listen on")
port := flag.Int("p", 8080, "The port to listen on")
token := flag.String("t", "", "The token to use to protect uploads")
flag.Parse()
boxHandler := BoxHandler {
"data",
*token,
}
err := os.MkdirAll(boxHandler.dataPath, 0750)
if err != nil {
log.Fatal(err)
}
log.Printf("Listening on %s:%d", *host, *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", *host, *port), boxHandler))
}
|