forked from h2non/imaginary
-
Notifications
You must be signed in to change notification settings - Fork 1
/
source_fs.go
60 lines (48 loc) · 1.25 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
package main
import (
"io/ioutil"
"net/http"
"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 {
return r.Method == http.MethodGet && s.getFileParam(r) != ""
}
func (s *FileSystemImageSource) GetImage(r *http.Request) ([]byte, error) {
file := s.getFileParam(r)
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 {
return r.URL.Query().Get("file")
}
func init() {
RegisterSource(ImageSourceTypeFileSystem, NewFileSystemImageSource)
}