-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdata.go
70 lines (57 loc) · 1.39 KB
/
data.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
package main
import (
"errors"
"io/ioutil"
"path/filepath"
"github.com/pierrre/imageserver"
imageserver_source "github.com/pierrre/imageserver/source"
)
var (
formats = map[string]string{
".jpeg": "jpeg",
".jpg": "jpeg",
".gif": "gif",
".png": "png",
}
// Server 使用文件名提供 server 服务
Server = imageserver.Server(imageserver.ServerFunc(func(params imageserver.Params) (*imageserver.Image, error) {
source, err := params.GetString(imageserver_source.Param)
if err != nil {
return nil, err
}
im, err := Get(source)
if err != nil {
return nil, &imageserver.ParamError{Param: imageserver_source.Param, Message: err.Error()}
}
return im, nil
}))
)
func Get(name string) (*imageserver.Image, error) {
format, err := GetFormat(name)
if err != nil {
return nil, err
}
return loadImage(name, format)
}
func GetFormat(filename string) (string, error) {
suffix := filepath.Ext(filename)
if suffix == "" {
return "", errors.New("invalid filename")
}
if format, has := formats[suffix]; has {
return format, nil
}
return "", errors.New("invalid filename")
}
func loadImage(filename string, format string) (*imageserver.Image, error) {
filePath := filepath.Join(config.ImagePath, filename)
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
im := &imageserver.Image{
Format: format,
Data: data,
}
return im, nil
}