forked from mtusi2026/mtusi2026lab6
70 lines
1.8 KiB
Go
70 lines
1.8 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type Server struct {
|
|
Host string
|
|
Port int
|
|
ReadTimeout time.Duration
|
|
WriteTimeout time.Duration
|
|
IdleTimeout time.Duration
|
|
ShutdownTimeout time.Duration
|
|
Enabled bool
|
|
}
|
|
|
|
func (c *Server) Validate() error {
|
|
if !c.Enabled {
|
|
return nil
|
|
}
|
|
switch {
|
|
case c.Host == "":
|
|
return wrapValidationError("server", errors.New("host cannot be empty"))
|
|
case c.Port == 0:
|
|
return wrapValidationError("server", errors.New("port cannot be empty"))
|
|
case c.ReadTimeout == 0:
|
|
return wrapValidationError("server", errors.New("read_timeout cannot be empty"))
|
|
case c.WriteTimeout == 0:
|
|
return wrapValidationError("server", errors.New("write_timeout cannot be empty"))
|
|
case c.IdleTimeout == 0:
|
|
return wrapValidationError("server", errors.New("idle_timeout cannot be empty"))
|
|
case c.ShutdownTimeout == 0:
|
|
return wrapValidationError("server", errors.New("shutdown_timeout name cannot be empty"))
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (c *Server) loadConfig(v *viper.Viper) error {
|
|
v.SetEnvPrefix("APP")
|
|
c.Host = v.GetString("HOST")
|
|
c.Port = v.GetInt("PORT")
|
|
c.ReadTimeout = v.GetDuration("READ_TIMEOUT")
|
|
c.WriteTimeout = v.GetDuration("WRITE_TIMEOUT")
|
|
c.IdleTimeout = v.GetDuration("IDLE_TIMEOUT")
|
|
c.ShutdownTimeout = v.GetDuration("SHUTDOWN_TIMEOUT")
|
|
c.Enabled = v.GetBool("ENABLED")
|
|
return c.Validate()
|
|
}
|
|
|
|
func (c *Server) BindAddress() string {
|
|
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
|
}
|
|
|
|
func (c *Server) copy() *Server {
|
|
return &Server{
|
|
Host: c.Host,
|
|
Port: c.Port,
|
|
ReadTimeout: c.ReadTimeout,
|
|
WriteTimeout: c.WriteTimeout,
|
|
IdleTimeout: c.IdleTimeout,
|
|
ShutdownTimeout: c.ShutdownTimeout,
|
|
Enabled: c.Enabled,
|
|
}
|
|
}
|