-
Notifications
You must be signed in to change notification settings - Fork 16
/
config.go
88 lines (74 loc) · 2.44 KB
/
config.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
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"runtime"
"gopkg.in/yaml.v2"
)
//Config is global configuration of the server
type Config struct {
DataDir string `yaml:"data_directory"`
DefaultImageQuality int `yaml:"default_image_quality"`
ServerAddress string `yaml:"server_address"`
Token string `yaml:"token"`
ValidImageSizes []string `yaml:"valid_image_sizes"`
ValidImageQualities []int `yaml:"valid_image_qualities"`
MaxUploadedImageSize int `yaml:"max_uploaded_image_size"` // in megabytes
HTTPCacheTTL int `yaml:"http_cache_ttl"`
LogPath string `yaml:"log_path"`
Debug bool `yaml:"debug"`
ConvertConcurrency int `yaml:"convert_concurrency"`
}
func getDefaultConfig() *Config {
return &Config{
DefaultImageQuality: 95,
ServerAddress: "127.0.0.1:8080",
ValidImageSizes: []string{"300x300", "500x500"},
MaxUploadedImageSize: 4,
HTTPCacheTTL: 2592000,
ConvertConcurrency: runtime.NumCPU(),
}
}
func parseConfig(file io.Reader) (*Config, error) {
cfg := getDefaultConfig()
buf, err := ioutil.ReadAll(file)
if err != nil {
return nil, fmt.Errorf("%+v\n", err)
}
if err := yaml.Unmarshal(buf, &cfg); err != nil {
return nil, fmt.Errorf("Invalid Config File: %v", err)
}
if token := os.Getenv("WEBP_SERVER_TOKEN"); len(token) != 0 {
cfg.Token = token
}
if cfg.DataDir == "" {
return nil, fmt.Errorf("Set data_directory in your config file.")
}
if !filepath.IsAbs(cfg.DataDir) {
return nil, fmt.Errorf("Absolute path for data_dir needed but got: %s", cfg.DataDir)
}
if len(cfg.LogPath) > 0 && !filepath.IsAbs(cfg.LogPath) {
return nil, fmt.Errorf("Absolute path for log_path needed but got: %s", cfg.LogPath)
}
if err := os.MkdirAll(cfg.DataDir, 0755); err != nil {
return nil, fmt.Errorf("%+v\n", err)
}
sizePattern := regexp.MustCompile("([0-9]{1,4})x([0-9]{1,4})")
for _, size := range cfg.ValidImageSizes {
match := sizePattern.FindAllString(size, -1)
if len(match) != 1 {
return nil, fmt.Errorf("Image size %s is not valid. Try use WIDTHxHEIGHT format.", size)
}
}
if cfg.DefaultImageQuality < 10 || cfg.DefaultImageQuality > 100 {
return nil, fmt.Errorf("Default image quality should be 10 < q < 100.")
}
if cfg.ConvertConcurrency <= 0 {
return nil, fmt.Errorf("Convert Concurrency should be greater than zero")
}
return cfg, nil
}