config
import "github.com/prescriptoo/prescriptoo-api/pkg/config"Package config provides generic environment configuration utilities.
Index
- func GetEnv(key, defaultValue string) string
- func GetEnvAsBool(key string, defaultValue bool) bool
- func GetEnvAsInt(key string, defaultValue int) int
- type Env
func GetEnv
func GetEnv(key, defaultValue string) stringGetEnv retrieves an environment variable or returns a default fallback value.
func GetEnvAsBool
func GetEnvAsBool(key string, defaultValue bool) boolGetEnvAsBool retrieves an environment variable as a boolean or returns a default fallback value.
func GetEnvAsInt
func GetEnvAsInt(key string, defaultValue int) intGetEnvAsInt retrieves an environment variable as an integer or returns a default fallback value.
type Env
Env contains application configuration. DatabaseURL and JWTSecret default to empty strings; dependencies must validate required values before using them.
type Env struct {
PatientDefaultPhoneRegion string
SubscriptionEnforcement string
Environment string
Port string
DatabaseURL string
RedisHost string
RedisPort string
RedisPassword string
RabbitMQURL string
JWTSecret string
JWTExpirationHours int
RefreshTokenExpirationDays int
}func LoadEnv
func LoadEnv(paths ...string) (Env, error)LoadEnv reads .env in the working directory, or an explicitly supplied file. A missing default .env is allowed. Process variables take precedence over file values, followed by defaults. It does not modify the process environment.
Example
LoadEnv accepts an explicit file, so tools can choose configuration without depending on the process working directory. Environment values take priority.
package main
import (
"fmt"
"os"
"github.com/prescriptoo/prescriptoo-api/pkg/config"
)
func main() {
// Fix values used by this example, restoring the caller's environment after it.
for key, value := range map[string]string{
"PORT": "9090", "JWT_EXPIRATION_HOURS": "1", "REFRESH_TOKEN_EXPIRATION_DAYS": "7",
} {
previous, exists := os.LookupEnv(key)
defer func() {
if exists {
_ = os.Setenv(key, previous)
} else {
_ = os.Unsetenv(key)
}
}()
if err := os.Setenv(key, value); err != nil {
panic(err)
}
}
file, err := os.CreateTemp("", "prescriptoo-config-*.env")
if err != nil {
panic(err)
}
defer func() {
if err := os.Remove(file.Name()); err != nil {
panic(err)
}
}()
if _, err := file.WriteString("DATABASE_URL=postgres://localhost/example\nPORT=8088\n"); err != nil {
panic(err)
}
if err := file.Close(); err != nil {
panic(err)
}
env, err := config.LoadEnv(file.Name())
if err != nil {
panic(err)
}
fmt.Println("Port:", env.Port)
fmt.Println("Access lifetime:", env.JWTExpirationHours)
}Output
Port: 9090
Access lifetime: 1Generated by gomarkdoc