forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Loader interface {
|
||||
loadConfig(v *viper.Viper) error
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
)
|
||||
|
||||
type Application struct {
|
||||
LogLevel string
|
||||
ShutdownTimeout time.Duration
|
||||
Environment environment.ApplicationEnvironment
|
||||
RequestRateLimit float64
|
||||
BurstRateLimit int
|
||||
RateLimitTTL time.Duration
|
||||
}
|
||||
|
||||
func (c *Application) Validate() error {
|
||||
environmentErr := c.Environment.Validate()
|
||||
|
||||
switch {
|
||||
case c.LogLevel == "":
|
||||
return wrapValidationError("application", errors.New("log_level cannot be empty in application config"))
|
||||
case c.ShutdownTimeout == 0:
|
||||
return wrapValidationError("application", errors.New("shutdown_timeout cannot be zero in application config"))
|
||||
case environmentErr != nil:
|
||||
return wrapValidationError("application", environmentErr)
|
||||
//case c.RequestRateLimit == 0:
|
||||
// return wrapValidationError("application", errors.New("request_rate_limit cannot be zero in application config"))
|
||||
//case c.BurstRateLimit == 0:
|
||||
// return wrapValidationError("application", errors.New("burst_rate_limit cannot be zero in application config"))
|
||||
//case c.RateLimitTTL == 0:
|
||||
// return wrapValidationError("application", errors.New("rate_limit_ttl cannot be zero in application config"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Application) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("APPLICATION")
|
||||
c.LogLevel = v.GetString("LOG_LEVEL")
|
||||
c.ShutdownTimeout = v.GetDuration("SHUTDOWN_TIMEOUT")
|
||||
c.Environment = environment.ParseEnvironment(v.GetString("ENVIRONMENT"))
|
||||
// todo add cool value
|
||||
c.RequestRateLimit = v.GetFloat64("REQUEST_RATE_LIMIT")
|
||||
c.BurstRateLimit = v.GetInt("BURST_RATE_LIMIT")
|
||||
c.RateLimitTTL = v.GetDuration("RATE_LIMIT_TTL")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Application) copy() *Application {
|
||||
return &Application{
|
||||
LogLevel: c.LogLevel,
|
||||
ShutdownTimeout: c.ShutdownTimeout,
|
||||
Environment: c.Environment,
|
||||
RequestRateLimit: c.RequestRateLimit,
|
||||
BurstRateLimit: c.BurstRateLimit,
|
||||
RateLimitTTL: c.RateLimitTTL,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
Endpoint, Region, Bucket, AccessKey, SecretKey string
|
||||
MaxBytes, MaxPixels int64
|
||||
Timeout, Grace time.Duration
|
||||
Uploads, Decoders int
|
||||
}
|
||||
|
||||
func LoadAttachment() (*Attachment, error) {
|
||||
c := &Attachment{Endpoint: env("S3_ENDPOINT", "http://s3:9000"), Region: env("S3_REGION", "us-east-1"), Bucket: env("S3_BUCKET", "messenger-attachments"), MaxBytes: 10485760, MaxPixels: 40000000, Timeout: 120 * time.Second, Grace: time.Hour, Uploads: 4, Decoders: 1}
|
||||
var err error
|
||||
for key, dst := range map[string]*string{"S3_ACCESS_KEY_ID_FILE": &c.AccessKey, "S3_SECRET_ACCESS_KEY_FILE": &c.SecretKey} {
|
||||
b, e := os.ReadFile(os.Getenv(key))
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", key, e)
|
||||
}
|
||||
*dst = strings.TrimSpace(string(b))
|
||||
if *dst == "" {
|
||||
return nil, fmt.Errorf("empty %s", key)
|
||||
}
|
||||
}
|
||||
for key, dst := range map[string]*int64{"MAX_UPLOAD_BYTES": &c.MaxBytes, "MAX_IMAGE_PIXELS": &c.MaxPixels} {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
*dst, err = strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
for key, dst := range map[string]*time.Duration{"UPLOAD_TIMEOUT": &c.Timeout, "RECONCILE_GRACE_PERIOD": &c.Grace} {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
*dst, err = time.ParseDuration(v)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.MaxBytes < 1 || c.MaxBytes > 10485760 || c.MaxPixels < 1 || c.MaxPixels > 40000000 || c.Timeout < time.Second || c.Timeout > 120*time.Second || c.Grace <= 2*c.Timeout {
|
||||
return nil, fmt.Errorf("invalid attachment limits or grace period")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func env(k, d string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"go.uber.org/multierr"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
)
|
||||
|
||||
var defaultConfig = &Config{
|
||||
Server: &Server{
|
||||
Host: "localhost",
|
||||
Port: 8001,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 10 * time.Second,
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
Enabled: false,
|
||||
},
|
||||
Postgres: &Postgres{
|
||||
Host: "localhost",
|
||||
Port: 5432,
|
||||
User: "postgres",
|
||||
Password: "postgres",
|
||||
Database: "postgres",
|
||||
VersionTable: "versions",
|
||||
RunMigrations: false,
|
||||
MaxConnections: 10,
|
||||
ConnectTimeout: 500 * time.Millisecond,
|
||||
QueryTimeout: 2 * time.Second,
|
||||
},
|
||||
Redis: &Redis{
|
||||
Host: "localhost",
|
||||
Port: 6379,
|
||||
Username: "",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
},
|
||||
JWT: &JWT{
|
||||
AccessTokenLifetime: 4 * time.Hour,
|
||||
RefreshTokenLifetime: time.Hour,
|
||||
PublicKeyPath: "certs/private.pem",
|
||||
PrivateKeyPath: "certs/public.pem",
|
||||
},
|
||||
Application: &Application{
|
||||
LogLevel: "info",
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
Environment: environment.ApplicationEnvironmentDev,
|
||||
RequestRateLimit: 100,
|
||||
},
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Server *Server
|
||||
Postgres *Postgres
|
||||
Redis *Redis
|
||||
JWT *JWT
|
||||
Application *Application
|
||||
}
|
||||
|
||||
func New() (*Config, error) {
|
||||
v := viper.New()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AutomaticEnv()
|
||||
|
||||
cfg := defaultConfig.copy()
|
||||
|
||||
if err := cfg.loadConfig(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
return multierr.Combine(
|
||||
c.Server.Validate(),
|
||||
c.Postgres.Validate(),
|
||||
c.JWT.Validate(),
|
||||
c.Redis.Validate(),
|
||||
c.Application.Validate(),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Config) loadConfig(v *viper.Viper) error {
|
||||
return multierr.Combine(
|
||||
c.Postgres.loadConfig(v),
|
||||
c.Server.loadConfig(v),
|
||||
c.JWT.loadConfig(v),
|
||||
c.Redis.loadConfig(v),
|
||||
c.Application.loadConfig(v),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Config) copy() *Config {
|
||||
return &Config{
|
||||
Server: c.Server.copy(),
|
||||
Postgres: c.Postgres.copy(),
|
||||
Redis: c.Redis.copy(),
|
||||
JWT: c.JWT.copy(),
|
||||
Application: c.Application.copy(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Cookies struct {
|
||||
Enabled bool
|
||||
Domain string
|
||||
Path string
|
||||
Secure bool
|
||||
SameSite http.SameSite
|
||||
AllowedOrigins []string
|
||||
}
|
||||
|
||||
func (c *Cookies) Validate() error {
|
||||
switch {
|
||||
case c.Domain == "":
|
||||
return wrapValidationError("cookies", errors.New("domain cannot be empty"))
|
||||
case c.Path == "":
|
||||
return wrapValidationError("cookies", errors.New("path cannot be empty"))
|
||||
case c.SameSite == http.SameSiteDefaultMode:
|
||||
return wrapValidationError("cookies", errors.New("same_site_set_to_none_mode cannot be empty"))
|
||||
//case c.Enabled && !c.Secure:
|
||||
// return wrapValidationError("cookies", errors.New("if cookies_enabled equals true then cookies_secure must be true"))
|
||||
case c.AllowedOrigins == nil || len(c.AllowedOrigins) == 0:
|
||||
return wrapValidationError("cookies", errors.New("allowed_origins cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cookies) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("COOKIES")
|
||||
c.Enabled = v.GetBool("ENABLED")
|
||||
c.Domain = v.GetString("DOMAIN")
|
||||
c.Path = v.GetString("PATH")
|
||||
c.Secure = v.GetBool("SECURE")
|
||||
c.AllowedOrigins = v.GetStringSlice("ALLOWED_ORIGINS")
|
||||
sameSite := v.GetString("SAME_SITE")
|
||||
switch strings.ToLower(strings.TrimSpace(sameSite)) {
|
||||
case "strict":
|
||||
c.SameSite = http.SameSiteStrictMode
|
||||
case "none":
|
||||
c.SameSite = http.SameSiteNoneMode
|
||||
default:
|
||||
c.SameSite = http.SameSiteLaxMode
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Cookies) copy() *Cookies {
|
||||
return &Cookies{
|
||||
Enabled: c.Enabled,
|
||||
Domain: c.Domain,
|
||||
Path: c.Path,
|
||||
Secure: c.Secure,
|
||||
SameSite: c.SameSite,
|
||||
AllowedOrigins: c.AllowedOrigins,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type JWT struct {
|
||||
AccessTokenLifetime time.Duration
|
||||
RefreshTokenLifetime time.Duration
|
||||
PublicKeyPath string
|
||||
PrivateKeyPath string
|
||||
}
|
||||
|
||||
func (c *JWT) Validate() error {
|
||||
switch {
|
||||
case c.AccessTokenLifetime <= 0:
|
||||
return wrapValidationError("jwt", errors.New("access_token_lifetime cannot be empty"))
|
||||
case c.RefreshTokenLifetime <= 0:
|
||||
return wrapValidationError("jwt", errors.New("refresh_token_lifetime cannot be empty"))
|
||||
case c.PrivateKeyPath == "":
|
||||
return wrapValidationError("jwt", errors.New("private_key_path cannot be empty"))
|
||||
case c.PublicKeyPath == "":
|
||||
return wrapValidationError("jwt", errors.New("public_key_path cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *JWT) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("JWT")
|
||||
c.AccessTokenLifetime = v.GetDuration("ACCESS_TOKEN_LIFETIME")
|
||||
c.RefreshTokenLifetime = time.Hour
|
||||
if value := os.Getenv("SESSION_TTL_SECONDS"); value != "" {
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds <= 0 || seconds > int64((1<<63-1)/time.Second) {
|
||||
return wrapValidationError("session", errors.New("SESSION_TTL_SECONDS must be a positive integer duration in seconds"))
|
||||
}
|
||||
c.RefreshTokenLifetime = time.Duration(seconds) * time.Second
|
||||
} else if legacy := v.GetString("REFRESH_TOKEN_LIFETIME"); legacy != "" {
|
||||
duration, err := time.ParseDuration(legacy)
|
||||
if err != nil {
|
||||
return wrapValidationError("jwt", errors.New("invalid refresh_token_lifetime"))
|
||||
}
|
||||
c.RefreshTokenLifetime = duration
|
||||
}
|
||||
c.PublicKeyPath = v.GetString("PUBLIC_KEY_PATH")
|
||||
c.PrivateKeyPath = v.GetString("PRIVATE_KEY_PATH")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *JWT) copy() *JWT {
|
||||
return &JWT{
|
||||
AccessTokenLifetime: c.AccessTokenLifetime,
|
||||
RefreshTokenLifetime: c.RefreshTokenLifetime,
|
||||
PublicKeyPath: c.PublicKeyPath,
|
||||
PrivateKeyPath: c.PrivateKeyPath,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Pipeline struct {
|
||||
Concurrency, Prefetch, MaxAttempts int
|
||||
Timeout, Lease, Retention time.Duration
|
||||
BrokerURL string
|
||||
}
|
||||
|
||||
func LoadPipeline() (*Pipeline, error) {
|
||||
c := &Pipeline{Concurrency: 2, Prefetch: 2, MaxAttempts: 5, Timeout: 60 * time.Second, Lease: 90 * time.Second, Retention: 24 * time.Hour}
|
||||
for k, p := range map[string]*int{"WORKER_CONCURRENCY": &c.Concurrency, "WORKER_PREFETCH": &c.Prefetch, "JOB_MAX_ATTEMPTS": &c.MaxAttempts} {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
n, e := strconv.Atoi(v)
|
||||
if e != nil || n < 1 || n > 64 {
|
||||
return nil, fmt.Errorf("invalid %s", k)
|
||||
}
|
||||
*p = n
|
||||
}
|
||||
}
|
||||
for k, p := range map[string]*time.Duration{"JOB_TIMEOUT": &c.Timeout, "JOB_LEASE": &c.Lease, "STAGING_RETENTION": &c.Retention} {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
d, e := time.ParseDuration(v)
|
||||
if e != nil || d <= 0 {
|
||||
return nil, fmt.Errorf("invalid %s", k)
|
||||
}
|
||||
*p = d
|
||||
}
|
||||
}
|
||||
if c.Lease <= c.Timeout || c.Prefetch > c.Concurrency {
|
||||
return nil, fmt.Errorf("lease must exceed timeout; prefetch must not exceed concurrency")
|
||||
}
|
||||
if p := os.Getenv("BROKER_URL_FILE"); p != "" {
|
||||
b, e := os.ReadFile(p)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("read broker secret: %w", e)
|
||||
}
|
||||
c.BrokerURL = strings.TrimSpace(string(b))
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
uri = "postgres://%s:%s@%s:%d/%s?sslmode=disable"
|
||||
)
|
||||
|
||||
type Postgres struct {
|
||||
Host string
|
||||
Port int
|
||||
User string
|
||||
Password string
|
||||
Database string
|
||||
VersionTable string
|
||||
RunMigrations bool
|
||||
MaxConnections int
|
||||
ConnectTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
}
|
||||
|
||||
func (c *Postgres) Validate() error {
|
||||
switch {
|
||||
case c.Host == "":
|
||||
return wrapValidationError("postgres", errors.New("host cannot be empty"))
|
||||
case c.Port == 0:
|
||||
return wrapValidationError("postgres", errors.New("port cannot be empty"))
|
||||
case c.User == "":
|
||||
return wrapValidationError("postgres", errors.New("user cannot be empty"))
|
||||
case c.Password == "":
|
||||
return wrapValidationError("postgres", errors.New("password cannot be empty"))
|
||||
case c.Database == "":
|
||||
return wrapValidationError("postgres", errors.New("database cannot be empty"))
|
||||
case c.VersionTable == "":
|
||||
return wrapValidationError("postgres", errors.New("version_table name cannot be empty"))
|
||||
case c.MaxConnections <= 0 || int64(c.MaxConnections) > math.MaxInt32:
|
||||
return wrapValidationError("postgres", errors.New("max_connections must be between 1 and 2147483647"))
|
||||
case c.ConnectTimeout <= 0:
|
||||
return wrapValidationError("postgres", errors.New("connect_timeout must be positive"))
|
||||
case c.QueryTimeout < time.Millisecond:
|
||||
return wrapValidationError("postgres", errors.New("query_timeout must be at least 1ms"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Postgres) GetMaxConnections() int32 { return int32(c.MaxConnections) }
|
||||
func (c *Postgres) GetConnectTimeout() time.Duration { return c.ConnectTimeout }
|
||||
func (c *Postgres) GetQueryTimeout() time.Duration { return c.QueryTimeout }
|
||||
|
||||
func (c *Postgres) GetVersionTableName() string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return c.VersionTable
|
||||
}
|
||||
|
||||
func (c *Postgres) GetURI() string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(uri, c.User, c.Password, c.Host, c.Port, c.Database)
|
||||
}
|
||||
|
||||
func (c *Postgres) GetRunMigrations() bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
return c.RunMigrations
|
||||
}
|
||||
|
||||
func (c *Postgres) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("POSTGRES")
|
||||
c.Host = v.GetString("HOST")
|
||||
c.Port = v.GetInt("PORT")
|
||||
c.User = v.GetString("USER")
|
||||
c.Password = v.GetString("PASSWORD")
|
||||
c.Database = v.GetString("DATABASE")
|
||||
c.VersionTable = v.GetString("VERSION_TABLE")
|
||||
c.RunMigrations = v.GetBool("RUN_MIGRATIONS")
|
||||
c.MaxConnections = v.GetInt("MAX_CONNECTIONS")
|
||||
c.ConnectTimeout = v.GetDuration("CONNECT_TIMEOUT")
|
||||
c.QueryTimeout = v.GetDuration("QUERY_TIMEOUT")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Postgres) copy() *Postgres {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Postgres{
|
||||
Host: c.Host,
|
||||
Port: c.Port,
|
||||
User: c.User,
|
||||
Password: c.Password,
|
||||
Database: c.Database,
|
||||
MaxConnections: c.MaxConnections,
|
||||
ConnectTimeout: c.ConnectTimeout,
|
||||
QueryTimeout: c.QueryTimeout,
|
||||
RunMigrations: c.RunMigrations,
|
||||
VersionTable: c.VersionTable,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Redis struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
DB int
|
||||
}
|
||||
|
||||
func (c *Redis) Validate() error {
|
||||
switch {
|
||||
case c.Host == "":
|
||||
return wrapValidationError("redis", errors.New("host cannot be empty"))
|
||||
case c.Port == 0:
|
||||
return wrapValidationError("redis", errors.New("port cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Redis) BuildRedisOptions() *redis.Options {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &redis.Options{
|
||||
Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)),
|
||||
Username: c.Username,
|
||||
Password: c.Password,
|
||||
DB: c.DB,
|
||||
DialTimeout: 200 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolTimeout: 200 * time.Millisecond,
|
||||
MaxRetries: -1,
|
||||
DialerRetries: 1,
|
||||
ContextTimeoutEnabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Redis) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("REDIS")
|
||||
c.Host = v.GetString("HOST")
|
||||
c.Port = v.GetInt("PORT")
|
||||
c.DB = v.GetInt("DB")
|
||||
c.Password = v.GetString("PASSWORD")
|
||||
c.Username = v.GetString("USERNAME")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Redis) copy() *Redis {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Redis{
|
||||
Host: c.Host,
|
||||
Port: c.Port,
|
||||
Username: c.Username,
|
||||
Password: c.Password,
|
||||
DB: c.DB,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package config
|
||||
|
||||
import "fmt"
|
||||
|
||||
func wrapValidationError(name string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s validation error: %w", name, err)
|
||||
}
|
||||
Reference in New Issue
Block a user