-
-
Notifications
You must be signed in to change notification settings - Fork 458
/
source_fs.go
75 lines (61 loc) · 1.51 KB
/
source_fs.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
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
)
const ImageSourceTypeFileSystem ImageSourceType = "fs"
type FileSystemImageSource struct {
Config *SourceConfig
}
func NewFileSystemImageSource(config *SourceConfig) ImageSource {
return &FileSystemImageSource{config}
}
func (s *FileSystemImageSource) Matches(r *http.Request) bool {
file, err := s.getFileParam(r)
if err != nil {
return false
}
return r.Method == http.MethodGet && file != ""
}
func (s *FileSystemImageSource) GetImage(r *http.Request) ([]byte, error) {
file, err := s.getFileParam(r)
if err != nil {
return nil, err
}
if file == "" {
return nil, ErrMissingParamFile
}
file, err = s.buildPath(file)
if err != nil {
return nil, err
}
return s.read(file)
}
func (s *FileSystemImageSource) buildPath(file string) (string, error) {
file = path.Clean(path.Join(s.Config.MountPath, file))
if !strings.HasPrefix(file, s.Config.MountPath) {
return "", ErrInvalidFilePath
}
return file, nil
}
func (s *FileSystemImageSource) read(file string) ([]byte, error) {
buf, err := ioutil.ReadFile(file)
if err != nil {
return nil, ErrInvalidFilePath
}
return buf, nil
}
func (s *FileSystemImageSource) getFileParam(r *http.Request) (string, error) {
unescaped, err := url.QueryUnescape(r.URL.Query().Get("file"))
if err != nil{
return "", fmt.Errorf("failed to unescape file param: %w", err)
}
return unescaped, nil
}
func init() {
RegisterSource(ImageSourceTypeFileSystem, NewFileSystemImageSource)
}