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
|
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/google/uuid"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
uid := uuid.New().String()
section := string(uid[len(uid)-1])
if err := os.MkdirAll(filepath.Join(path, section), 0777); err != nil {
log.Println(err)
http.Error(w, "can't create storage dir", http.StatusInternalServerError)
return
}
fp, err := os.Create(filepath.Join(path, section, uid))
if err != nil {
log.Println(err)
http.Error(w, "can't create storage file", http.StatusInternalServerError)
return
}
defer fp.Close()
if _, err := io.Copy(fp, r.Body); err != nil {
log.Println(err)
http.Error(w, "can't upload storage file", http.StatusInternalServerError)
return
}
h := w.Header()
h.Set("Content-Type", "text/plain; charset=utf-8")
h.Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusCreated)
u, err := url.JoinPath(host, section, uid)
if err != nil {
log.Println(err)
http.Error(w, "can't get file url", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, u)
}
|