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
|
package main
import (
"net/http"
"html/template"
"log"
"fmt"
"embed"
"io"
"os"
"path"
"path/filepath"
)
//go:embed templates
var tmplFS embed.FS
type BoxHandler struct {
dataPath string
}
func serve(w http.ResponseWriter, views ...string) {
t, err := template.New("index.html").ParseFS(tmplFS, views...)
if err != nil {
log.Fatal(err)
}
if err := t.Execute(w, nil); err != nil {
log.Fatal(err)
}
}
func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
serve(w, "templates/index.html")
return
case http.MethodPost:
filename := filepath.Join(handler.dataPath, path.Base(r.URL.Path))
log.Printf("boxing %s\n", filename)
f, err := os.Create(filename)
if err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
io.Copy(f, r.Body)
log.Printf("boxed %s\n", filename)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
boxHandler := BoxHandler {
"data",
}
err := os.MkdirAll(boxHandler.dataPath, 0750)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", boxHandler))
}
|