mirror of
https://github.com/derfenix/webarchive.git
synced 2026-03-11 12:41:54 +03:00
Extend configuration
This commit is contained in:
54
config/config.go
Normal file
54
config/config.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sethvargo/go-envconfig"
|
||||
)
|
||||
|
||||
const envPrefix = "WEBARCHIVE_"
|
||||
|
||||
func NewConfig(ctx context.Context) (Config, error) {
|
||||
cfg := Config{}
|
||||
|
||||
lookuper := envconfig.MultiLookuper(
|
||||
envconfig.PrefixLookuper(envPrefix, envconfig.OsLookuper()),
|
||||
envconfig.OsLookuper(),
|
||||
)
|
||||
|
||||
if err := envconfig.ProcessWith(ctx, &cfg, lookuper); err != nil {
|
||||
return Config{}, fmt.Errorf("process env: %w", err)
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
DB DB `env:",prefix=DB_"`
|
||||
Logging Logging `env:",prefix=LOGGING_"`
|
||||
API API `env:",prefix=API_"`
|
||||
PDF PDF `env:",prefix=PDF_"`
|
||||
}
|
||||
|
||||
type PDF struct {
|
||||
Landscape bool `env:"LANDSCAPE,default=false"`
|
||||
Grayscale bool `env:"GRAYSCALE,default=false"`
|
||||
MediaPrint bool `env:"MEDIA_PRINT,default=true"`
|
||||
Zoom float64 `env:"ZOOM,default=1"`
|
||||
Viewport string `env:"VIEWPORT,default=1920x1080"`
|
||||
DPI uint `env:"DPI,default=300"`
|
||||
Filename string `env:"FILENAME,default=page.pdf"`
|
||||
}
|
||||
|
||||
type API struct {
|
||||
Address string `env:"ADDRESS,default=0.0.0.0:5001"`
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
Path string `env:"PATH,default=./db"`
|
||||
}
|
||||
|
||||
type Logging struct {
|
||||
Debug bool `env:"DEBUG"`
|
||||
}
|
||||
42
config/config_test.go
Normal file
42
config/config_test.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewConfig(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("no envs", func(t *testing.T) {
|
||||
|
||||
config, err := NewConfig(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "./db", config.DB.Path)
|
||||
})
|
||||
|
||||
t.Run("env without prefix", func(t *testing.T) {
|
||||
require.NoError(t, os.Setenv("DB_PATH", "./old_db"))
|
||||
|
||||
config, err := NewConfig(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "./old_db", config.DB.Path)
|
||||
})
|
||||
|
||||
t.Run("prefix env override", func(t *testing.T) {
|
||||
require.NoError(t, os.Setenv("WEBARCHIVE_DB_PATH", "./new_db"))
|
||||
|
||||
config, err := NewConfig(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "./new_db", config.DB.Path)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user