Начало реализации сервиса.

This commit is contained in:
Grbisba
2026-10-30 12:25:56 +03:00
parent 65003b6119
commit 20f2f00a60
52 changed files with 4351 additions and 1 deletions
+7
View File
@@ -0,0 +1,7 @@
package config
import "github.com/spf13/viper"
type Loader interface {
loadConfig(v *viper.Viper) error
}
+63
View File
@@ -0,0 +1,63 @@
package config
import (
"errors"
"time"
"github.com/spf13/viper"
"gitea.privcloud.tech/mtusi2026/internal/pkg/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,
}
}
+121
View File
@@ -0,0 +1,121 @@
package config
import (
"net/http"
"strings"
"time"
"github.com/spf13/viper"
"go.uber.org/multierr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/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,
},
Redis: &Redis{
Host: "localhost",
Port: 6379,
Username: "",
Password: "",
DB: 0,
},
JWT: &JWT{
AccessTokenLifetime: 4 * time.Hour,
RefreshTokenLifetime: 24 * time.Hour,
PublicKeyPath: "certs/private.pem",
PrivateKeyPath: "certs/public.pem",
},
Cookies: &Cookies{
Enabled: true,
Domain: "",
Path: "/",
Secure: true,
SameSite: http.SameSiteStrictMode,
AllowedOrigins: []string{"http:localhost:8080"},
},
Application: &Application{
LogLevel: "info",
ShutdownTimeout: 10 * time.Second,
Environment: environment.ApplicationEnvironmentDev,
RequestRateLimit: 100,
},
}
type Config struct {
Server *Server
Postgres *Postgres
Redis *Redis
JWT *JWT
Cookies *Cookies
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.Cookies.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.Cookies.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(),
Cookies: c.Cookies.copy(),
Application: c.Application.copy(),
}
}
+65
View File
@@ -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,
}
}
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"errors"
"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 = v.GetDuration("REFRESH_TOKEN_LIFETIME")
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,
}
}
+94
View File
@@ -0,0 +1,94 @@
package config
import (
"errors"
"fmt"
"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
}
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:
return wrapValidationError("postgres", errors.New("max_connections cannot be empty"))
default:
return nil
}
}
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")
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,
RunMigrations: c.RunMigrations,
VersionTable: c.VersionTable,
}
}
+64
View File
@@ -0,0 +1,64 @@
package config
import (
"errors"
"fmt"
"net"
"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,
}
}
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,
}
}
+96
View File
@@ -0,0 +1,96 @@
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
}
// LoadServer reads settings from environment variables and applies lab1 defaults.
func LoadServer() (*Server, error) {
v := viper.New()
v.SetEnvPrefix("APP")
v.AutomaticEnv()
v.SetDefault("HOST", "0.0.0.0")
v.SetDefault("PORT", 8080)
v.SetDefault("READ_TIMEOUT", "5s")
v.SetDefault("WRITE_TIMEOUT", "10s")
v.SetDefault("IDLE_TIMEOUT", "60s")
v.SetDefault("SHUTDOWN_TIMEOUT", "10s")
v.SetDefault("ENABLED", true)
if err := v.BindEnv("HOST", "APP_HOST", "SERVER_HOST"); err != nil {
return nil, err
}
if err := v.BindEnv("PORT", "APP_PORT", "SERVER_PORT"); err != nil {
return nil, err
}
cfg := new(Server)
if err := cfg.loadConfig(v); err != nil {
return nil, err
}
return cfg, nil
}
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,
}
}
+11
View File
@@ -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)
}