Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func LoadString ¶
LoadString loads configuration from a string with optional environment variable support. Parameters:
- configString: The configuration string in YAML format
- envPrefix: Optional environment variable prefix (default: "ENV"). Only the first value is used; any additional values are ignored.
Example ¶
Basic loading from a YAML string, plus the default ENV_ override mechanism. Examples have no *testing.T, so environment variables are managed with os.Setenv/os.Unsetenv directly.
package main
import (
"fmt"
"os"
"github.com/jasoet/pkg/v3/config"
)
func main() {
type AppConfig struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
Server struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"server"`
}
yamlConfig := `
name: my-app
version: 1.0.0
server:
host: localhost
port: 8080
`
// Dots become underscores: server.port is overridden by ENV_SERVER_PORT.
os.Setenv("ENV_SERVER_PORT", "9090")
defer os.Unsetenv("ENV_SERVER_PORT")
cfg, err := config.LoadString[AppConfig](yamlConfig)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("%s v%s on %s:%d\n", cfg.Name, cfg.Version, cfg.Server.Host, cfg.Server.Port)
}
Output: my-app v1.0.0 on localhost:9090
func LoadStringWithOptions ¶
LoadStringWithOptions loads configuration from a string with optional environment variable support and applies the given options before unmarshaling. Options run after the YAML has been parsed; options that must precede parsing are not supported. Parameters:
- configString: The configuration string in YAML format
- opts: Options to customize the viper configuration before unmarshaling
Example ¶
Loading with functional options: defaults for missing keys and a custom environment variable prefix.
package main
import (
"fmt"
"os"
"github.com/jasoet/pkg/v3/config"
)
func main() {
type AppConfig struct {
Debug bool `yaml:"debug"`
Server struct {
Port int `yaml:"port"`
} `yaml:"server"`
}
os.Setenv("APP_SERVER_PORT", "9090")
defer os.Unsetenv("APP_SERVER_PORT")
cfg, err := config.LoadStringWithOptions[AppConfig](`server: {port: 8080}`,
config.WithDefaults(map[string]any{"debug": true}),
config.WithEnvPrefix("APP"),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("debug=%v port=%d\n", cfg.Debug, cfg.Server.Port)
}
Output: debug=true port=9090
Types ¶
type Option ¶
Option customizes the viper configuration used during loading. Consumers use the provided With* constructors and never need to name viper.
func WithDefaults ¶
WithDefaults sets default values for the given keys.
func WithEnvPrefix ¶
WithEnvPrefix sets the environment variable prefix used for lookups.
func WithNestedEnvVars ¶
WithNestedEnvVars processes environment variables with the given prefix and sets them under configPath, filling only keys absent from the loaded configuration. Parameters:
- prefix: The prefix of environment variables to process (e.g. "MY_APP_").
- keyDepth: The zero-based index into the underscore-split key after the prefix has been removed, at which the entity name token is located. For example, given the env var MY_APP_USER_NAME with prefix "MY_APP_", the remaining parts are ["USER", "NAME"]. With keyDepth=0, "USER" is treated as the entity name and "NAME" becomes the field name.
- configPath: The base path in the configuration where values should be set.
Example ¶
WithNestedEnvVars maps prefixed environment variables onto a map-typed config section. The prefix is stripped first, then keyDepth indexes the remaining underscore-split tokens: with prefix "APP" and keyDepth 1, APP_USERS_ADMIN_NAME yields entity "admin" with field "name" under the "users" config path.
Precedence contract: nested env vars fill only keys absent from the YAML. Here users.admin.name comes from YAML, so APP_USERS_ADMIN_NAME is ignored, while users.admin.email is YAML-absent and filled from the environment.
package main
import (
"fmt"
"os"
"github.com/jasoet/pkg/v3/config"
)
func main() {
type Config struct {
Users map[string]map[string]string `yaml:"users"`
}
os.Setenv("APP_USERS_ADMIN_NAME", "alice")
os.Setenv("APP_USERS_ADMIN_EMAIL", "alice@example.com")
defer os.Unsetenv("APP_USERS_ADMIN_NAME")
defer os.Unsetenv("APP_USERS_ADMIN_EMAIL")
cfg, err := config.LoadStringWithOptions[Config](`users: {admin: {name: bob}}`,
config.WithNestedEnvVars("APP", 1, "users"),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.Users["admin"]["name"])
fmt.Println(cfg.Users["admin"]["email"])
}
Output: bob alice@example.com