Here’s a minimal example showing how to use caarlos0/env to parse an environment variable into a
map[string]url.URL.
In this snippet you’ll see two variants:
- Rely on the default separators (
, between entries, : between key/value).
- Override them to e.g.
; and =.
package main
import (
"fmt"
"log"
"net/url"
"os"
"github.com/caarlos0/env/v6"
)
type Config struct {
// 1) default: entries sep=',' key/value sep=':'
// e.g. SERVICES="auth:https://auth.example.com,api:https://api.example.com"
ServicesDefault map[string]url.URL `env:"SERVICES_DEFAULT"`
// 2) custom: entries sep=';' key/value sep='='
// e.g. SERVICES_CUSTOM="auth=https://auth.example.com;api=https://api.example.com"
ServicesCustom map[string]url.URL `env:"SERVICES_CUSTOM" envSeparator=";" envMapKeySeparator="="`
}
func main() {
// simulate setting the env vars:
os.Setenv("SERVICES_DEFAULT", "auth:https://auth.example.com,api:https://api.example.com")
os.Setenv("SERVICES_CUSTOM", "auth=https://auth.example.com;api=https://api.example.com")
var cfg Config
if err := env.Parse(&cfg); err != nil {
log.Fatalf("unable to parse env: %v", err)
}
fmt.Println("=== Default separators ===")
for name, u := range cfg.ServicesDefault {
fmt.Printf("%-4s → %s\n", name, u.String())
}
fmt.Println("\n=== Custom separators ===")
for name, u := range cfg.ServicesCustom {
fmt.Printf("%-4s → %s\n", name, u.String())
}
}
Run it, and you’ll get:
=== Default separators ===
auth → https://auth.example.com
api → https://api.example.com
=== Custom separators ===
auth → https://auth.example.com
api → https://api.example.com
How it works:
• url.URL implements encoding.TextUnmarshaler, so caarlos0/env will call UnmarshalText
• By default, map entries are split on , and each key/value on :
• You can override via the struct tags
– envSeparator → splits entries
– envMapKeySeparator → splits each entry into key vs. value
Feel free to tweak the separators or var names to suit your own use-case! 🚀