|
6 | 6 | "encoding/hex" |
7 | 7 | "fmt" |
8 | 8 | "log/slog" |
| 9 | + "net/url" |
9 | 10 | "os" |
10 | 11 | "reflect" |
11 | 12 | "runtime" |
@@ -91,6 +92,38 @@ type config struct { |
91 | 92 | appName string |
92 | 93 | } |
93 | 94 |
|
| 95 | +// NewConfig merges configuration from two sources in order of precedence: |
| 96 | +// 1. programmatic configuration |
| 97 | +// 2. environment variables |
| 98 | +// Finally, it applies default values if needed. |
| 99 | +func NewConfig(programmaticConfig config) *config { |
| 100 | + dbosConfig := &config{} |
| 101 | + |
| 102 | + // Start with environment variables (lowest precedence) |
| 103 | + if dbURL := os.Getenv("DBOS_DATABASE_URL"); dbURL != "" { |
| 104 | + dbosConfig.databaseURL = dbURL |
| 105 | + } |
| 106 | + |
| 107 | + // Override with programmatic configuration (highest precedence) |
| 108 | + if len(programmaticConfig.databaseURL) > 0 { |
| 109 | + dbosConfig.databaseURL = programmaticConfig.databaseURL |
| 110 | + } |
| 111 | + if len(programmaticConfig.appName) > 0 { |
| 112 | + dbosConfig.appName = programmaticConfig.appName |
| 113 | + } |
| 114 | + // Copy over parameters that can only be set programmatically |
| 115 | + dbosConfig.logger = programmaticConfig.logger |
| 116 | + dbosConfig.adminServer = programmaticConfig.adminServer |
| 117 | + |
| 118 | + // Load defaults |
| 119 | + if len(dbosConfig.databaseURL) == 0 { |
| 120 | + getLogger().Info("DBOS_DATABASE_URL not set, using default: postgres://postgres:${PGPASSWORD}@localhost:5432/dbos?sslmode=disable") |
| 121 | + password := url.QueryEscape(os.Getenv("PGPASSWORD")) |
| 122 | + dbosConfig.databaseURL = fmt.Sprintf("postgres://postgres:%s@localhost:5432/dbos?sslmode=disable", password) |
| 123 | + } |
| 124 | + return dbosConfig |
| 125 | +} |
| 126 | + |
94 | 127 | type LaunchOption func(*config) |
95 | 128 |
|
96 | 129 | func WithLogger(logger *slog.Logger) LaunchOption { |
|
0 commit comments