Files
MyGoServer/cmd/apiserver/config/config.go

79 lines
1.6 KiB
Go

package config
import (
"flag"
"log"
"time"
"github.com/BurntSushi/toml"
)
type Server struct {
Address string `toml:"address"`
ReadTimeout time.Duration `toml:"read_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
IdleTimeout time.Duration `toml:"idle_timeout"`
}
type Logging struct {
Level string `toml:"level"`
Format string `toml:"format"`
Output string `toml:"output"`
}
type Request struct {
MaxBodySize int64 `toml:"max_body_size"`
}
type Config struct {
Server Server `toml:"server"`
Logging Logging `toml:"logging"`
Request Request `toml:"request"`
}
var (
configPath string
)
func init() {
flag.StringVar(&configPath, "config-path", "./configs/development.toml", "path to config")
}
func Load() *Config {
flag.Parse()
var config Config
if _, err := toml.DecodeFile(configPath, &config); err != nil {
log.Fatalf("Failed to load config: %v", err)
}
// Set defaults if not specified
if config.Server.Address == "" {
config.Server.Address = ":8080"
}
if config.Server.ReadTimeout == 0 {
config.Server.ReadTimeout = 10 * time.Second
}
if config.Server.WriteTimeout == 0 {
config.Server.WriteTimeout = 10 * time.Second
}
if config.Server.IdleTimeout == 0 {
config.Server.IdleTimeout = 60 * time.Second
}
if config.Logging.Level == "" {
config.Logging.Level = "info"
}
if config.Logging.Format == "" {
config.Logging.Format = "json"
}
if config.Logging.Output == "" {
config.Logging.Output = "stdout"
}
if config.Request.MaxBodySize == 0 {
config.Request.MaxBodySize = 10 * 1024 * 1024 // 10MB
}
return &config
}