sub2clash/config/config.go

102 lines
2.3 KiB
Go
Raw Normal View History

2023-09-12 18:40:24 +08:00
package config
2023-09-13 00:46:17 +08:00
import (
"errors"
2023-09-13 00:46:17 +08:00
"os"
"regexp"
2023-09-13 00:46:17 +08:00
"strconv"
"github.com/joho/godotenv"
2023-09-13 00:46:17 +08:00
)
2023-09-12 18:40:24 +08:00
type Config struct {
2023-09-13 00:46:17 +08:00
Port int
MetaTemplate string
ClashTemplate string
RequestRetryTimes int
RequestMaxFileSize int64
2023-09-13 13:47:22 +08:00
CacheExpire int64
LogLevel string
2023-09-27 14:54:53 +08:00
//BasePath string
ShortLinkLength int
2023-09-12 18:40:24 +08:00
}
var Default *Config
var Version string
var Dev string
2023-09-12 18:40:24 +08:00
func init() {
reg := regexp.MustCompile(`^v\d+\.\d+\.\d+$`)
if reg.MatchString(Version) {
Dev = "false"
} else {
Dev = "true"
}
}
func LoadConfig() error {
2023-09-12 18:40:24 +08:00
Default = &Config{
2023-09-13 00:46:17 +08:00
MetaTemplate: "template_meta.yaml",
ClashTemplate: "template_clash.yaml",
RequestRetryTimes: 3,
RequestMaxFileSize: 1024 * 1024 * 1,
Port: 8011,
2023-09-13 13:47:22 +08:00
CacheExpire: 60 * 5,
LogLevel: "info",
2023-09-27 14:54:53 +08:00
//BasePath: "/",
ShortLinkLength: 6,
2023-09-13 00:46:17 +08:00
}
2023-09-17 17:02:59 +08:00
_ = godotenv.Load()
2023-09-13 00:46:17 +08:00
if os.Getenv("PORT") != "" {
atoi, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
return errors.New("PORT invalid")
2023-09-13 00:46:17 +08:00
}
Default.Port = atoi
}
if os.Getenv("META_TEMPLATE") != "" {
Default.MetaTemplate = os.Getenv("META_TEMPLATE")
}
if os.Getenv("CLASH_TEMPLATE") != "" {
Default.ClashTemplate = os.Getenv("CLASH_TEMPLATE")
}
if os.Getenv("REQUEST_RETRY_TIMES") != "" {
atoi, err := strconv.Atoi(os.Getenv("REQUEST_RETRY_TIMES"))
if err != nil {
return errors.New("REQUEST_RETRY_TIMES invalid")
2023-09-13 00:46:17 +08:00
}
Default.RequestRetryTimes = atoi
}
if os.Getenv("REQUEST_MAX_FILE_SIZE") != "" {
atoi, err := strconv.Atoi(os.Getenv("REQUEST_MAX_FILE_SIZE"))
if err != nil {
return errors.New("REQUEST_MAX_FILE_SIZE invalid")
2023-09-13 00:46:17 +08:00
}
Default.RequestMaxFileSize = int64(atoi)
2023-09-12 18:40:24 +08:00
}
2023-09-13 13:47:22 +08:00
if os.Getenv("CACHE_EXPIRE") != "" {
atoi, err := strconv.Atoi(os.Getenv("CACHE_EXPIRE"))
if err != nil {
return errors.New("CACHE_EXPIRE invalid")
2023-09-13 13:47:22 +08:00
}
Default.CacheExpire = int64(atoi)
}
if os.Getenv("LOG_LEVEL") != "" {
Default.LogLevel = os.Getenv("LOG_LEVEL")
}
2023-09-27 14:54:53 +08:00
//if os.Getenv("BASE_PATH") != "" {
// Default.BasePath = os.Getenv("BASE_PATH")
// if Default.BasePath[len(Default.BasePath)-1] != '/' {
// Default.BasePath += "/"
// }
//}
if os.Getenv("SHORT_LINK_LENGTH") != "" {
atoi, err := strconv.Atoi(os.Getenv("SHORT_LINK_LENGTH"))
if err != nil {
return errors.New("SHORT_LINK_LENGTH invalid")
}
Default.ShortLinkLength = atoi
}
return nil
2023-09-12 18:40:24 +08:00
}