-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiles.go
More file actions
98 lines (85 loc) · 1.96 KB
/
Copy pathfiles.go
File metadata and controls
98 lines (85 loc) · 1.96 KB
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
package main
import (
"regexp"
"fmt"
"log"
"net/http"
"politics/go/entry"
"politics/go/entry/helper"
"politics/go/server"
"strings"
"path/filepath"
"time"
)
func files(s *server.Server, w http.ResponseWriter, r *http.Request) {
e, err := getEntry(s.Files, r.URL.Path)
if err != nil {
http.NotFound(w, r)
log.Println(err)
return
}
serveSingleBlob(w, r, e)
}
func serveSingleBlob(w http.ResponseWriter, r *http.Request, e entry.Entry) error {
blob, ok := e.(entry.Blob)
if !ok {
return fmt.Errorf("File to serve (%v) is no blob.", e.File().Name())
}
serveStatic(w, r, blob.Location(""))
return nil
}
func getEntry(files entry.Entries, path string) (entry.Entry, error) {
hash, err := getHash(path)
if err != nil {
return nil, err
}
id, err := helper.ParseHash(hash)
if err != nil {
return nil, err
}
for _, e := range files {
if e.Id() == id {
return e, nil
}
}
return nil, fmt.Errorf("getEntry: Id %v (%v) not found.", id, helper.ToTimestamp(id))
}
func getHash(path string) (string, error) {
p, err := validPath(path)
if err != nil {
return "", err
}
rel := p[len("/files/"):]
i := strings.Index(rel, ".")
if i < 1 {
return "", fmt.Errorf("invalid hash")
}
return rel[:i], nil
}
var valid = regexp.MustCompile(`^\/[0-9a-z+-_.\/]*$`)
func validPath(foreign string) (string, error) {
if valid.MatchString(foreign) {
return foreign, nil
}
return "", fmt.Errorf("invalid Path: %v", foreign)
}
func serveStatic(w http.ResponseWriter, r *http.Request, p string) {
if filepath.Ext(p) == ".vtt" {
w.Header().Set("Content-Type", "text/vtt")
}
w.Header().Set("Expires", time.Now().AddDate(0, 3, 0).Format(time.RFC1123))
http.ServeFile(w, r, p)
}
func static(s *server.Server, w http.ResponseWriter, r *http.Request) {
path, err := validPath(r.URL.Path)
if err != nil {
http.NotFound(w, r)
return
}
// Block folders.
if strings.HasSuffix(path, "/") {
http.NotFound(w, r)
return
}
serveStatic(w, r, s.Paths.Root+path)
}