{"id":13410895,"url":"https://github.com/syntaqx/env","last_synced_at":"2025-12-26T06:02:39.303Z","repository":{"id":244141130,"uuid":"814390059","full_name":"syntaqx/env","owner":"syntaqx","description":"An environment variable utility package","archived":false,"fork":false,"pushed_at":"2024-07-18T07:59:17.000Z","size":240,"stargazers_count":3,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-07-31T20:44:15.875Z","etag":null,"topics":["environment-variables","golang"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/syntaqx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["syntaqx"]}},"created_at":"2024-06-12T23:24:35.000Z","updated_at":"2024-07-18T07:58:06.000Z","dependencies_parsed_at":"2024-11-01T05:30:49.267Z","dependency_job_id":null,"html_url":"https://github.com/syntaqx/env","commit_stats":null,"previous_names":["syntaqx/env"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/syntaqx%2Fenv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/syntaqx%2Fenv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/syntaqx%2Fenv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/syntaqx%2Fenv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/syntaqx","download_url":"https://codeload.github.com/syntaqx/env/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243610525,"owners_count":20318977,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["environment-variables","golang"],"created_at":"2024-07-30T20:01:10.059Z","updated_at":"2025-12-26T06:02:39.226Z","avatar_url":"https://github.com/syntaqx.png","language":"Go","funding_links":["https://github.com/sponsors/syntaqx"],"categories":["配置","Configuration"],"sub_categories":["标准CLI","Standard CLI"],"readme":"# env\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/syntaqx/env.svg)](https://pkg.go.dev/github.com/syntaqx/env)\n[![codecov](https://codecov.io/gh/syntaqx/env/graph/badge.svg?token=m4bBKy3UG3)](https://codecov.io/gh/syntaqx/env)\n[![Go Report Card](https://goreportcard.com/badge/github.com/syntaqx/env)](https://goreportcard.com/report/github.com/syntaqx/env)\n[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)\n\n`env` is an environment variable utility package for Go. It provides simple\nfunctions to get and set environment variables, including support for\nunmarshalling environment variables into structs with support for nested\nstructures, default values, and required fields.\n\n## Features\n\n- __Basic Get/Set__: Simple functions to get, set, and unset environment variables.\n- __Type Conversion__: Functions to get environment variables as different types (int, bool, float).\n- __Fallback Values__: Support for fallback values if an environment variable is not set.\n- __Unmarshal__: Load environment variables into structs using struct tags.\n- __Nested Structs__: Support for nested struct prefixes to group environment variables.\n\n## Installation\n\n```sh\ngo get github.com/syntaqx/env\n```\n\n## Basic Usage\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/syntaqx/env\"\n)\n\nfunc main() {\n    port := env.GetWithFallback(\"PORT\", \"8080\")\n    fmt.Printf(\"Port: %s\\n\", port)\n\n    // Assuming the value of HOSTS is a comma-separated list of strings\n    // Example: some-host:8000,another-host:8000\n    hosts, err := env.GetStringSliceWithFallback(\"HOSTS\", []string{\"fallback-host-1:8000\", \"fallback-host-2:8000\"})\n    if err != nil {\n        fmt.Printf(\"Error getting hosts: %v\\n\", err)\n    } else {\n        fmt.Printf(\"Hosts: %v\\n\", hosts)\n    }\n}\n```\n\n## Unmarshal to Struct\n\nThe `Unmarshal` function allows you to load environment variables into a struct\nbased on struct tags. You can use `default` or `fallback` for fallback values\nand `required` to enforce that an environment variable must be set.\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n\n    \"github.com/syntaqx/env\"\n)\n\ntype DatabaseConfig struct {\n    Host     string `env:\"DATABASE_HOST,default=localhost\"`\n    Port     int    `env:\"DATABASE_PORT|DB_PORT,fallback=3306\"`\n    Username string `env:\"DATABASE_USERNAME,default=root\"`\n    Password string `env:\"DATABASE_PASSWORD,required\"`\n    Database string `env:\"DATABASE_NAME\"`\n}\n\ntype Config struct {\n    Debug    bool           `env:\"DEBUG\"`\n    Port     string         `env:\"PORT,default=8080\"`\n    Database DatabaseConfig\n}\n\nfunc main() {\n    var cfg Config\n\n    // Set example environment variables\n    _ = env.Set(\"DEBUG\", \"true\")\n    _ = env.Set(\"PORT\", \"9090\")\n    _ = env.Set(\"DATABASE_HOST\", \"dbhost\")\n    _ = env.Set(\"DATABASE_PORT\", \"5432\")\n    _ = env.Set(\"DATABASE_USERNAME\", \"admin\")\n    _ = env.Set(\"DATABASE_PASSWORD\", \"secret\")\n    _ = env.Set(\"DATABASE_NAME\", \"mydb\")\n\n    if err := env.Unmarshal(\u0026cfg); err != nil {\n        log.Fatalf(\"Error unmarshalling config: %v\", err)\n    }\n\n    fmt.Printf(\"Config: %+v\\n\", cfg)\n}\n```\n\n### Nested Struct Prefixes\n\nYou can use nested prefixes to group environment variables. This allows you to\nreuse the same struct in multiple places without having to worry about\nconflicting environment variables.\n\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n\n    \"github.com/syntaqx/env\"\n)\n\ntype DatabaseConfig struct {\n    Host     string `env:\"HOST,default=localhost\"`\n    Port     int    `env:\"PORT,fallback=3306\"`\n    Username string `env:\"USERNAME,default=root\"`\n    Password string `env:\"PASSWORD,required\"`\n    Database string `env:\"NAME\"`\n}\n\ntype Config struct {\n    Debug         bool           `env:\"DEBUG\"`\n    Port          string         `env:\"PORT,default=8080\"`\n    ReadDatabase  DatabaseConfig `env:\"READ_DATABASE\"`\n    WriteDatabase DatabaseConfig `env:\"WRITE_DATABASE\"`\n}\n\nfunc main() {\n    var cfg Config\n\n    // Set example environment variables\n    _ = env.Set(\"DEBUG\", \"true\")\n    _ = env.Set(\"PORT\", \"9090\")\n    _ = env.Set(\"READ_DATABASE_HOST\", \"read-dbhost\")\n    _ = env.Set(\"READ_DATABASE_PORT\", \"5432\")\n    _ = env.Set(\"READ_DATABASE_USERNAME\", \"read-admin\")\n    _ = env.Set(\"READ_DATABASE_PASSWORD\", \"read-secret\")\n    _ = env.Set(\"READ_DATABASE_NAME\", \"read-mydb\")\n    _ = env.Set(\"WRITE_DATABASE_HOST\", \"write-dbhost\")\n    _ = env.Set(\"WRITE_DATABASE_PORT\", \"5432\")\n    _ = env.Set(\"WRITE_DATABASE_USERNAME\", \"write-admin\")\n    _ = env.Set(\"WRITE_DATABASE_PASSWORD\", \"write-secret\")\n    _ = env.Set(\"WRITE_DATABASE_NAME\", \"write-mydb\")\n\n    if err := env.Unmarshal(\u0026cfg); err != nil {\n        log.Fatalf(\"Error unmarshalling config: %v\", err)\n    }\n\n    fmt.Printf(\"Config: %+v\\n\", cfg)\n}\n```\n\n### Slice Types Defaults\n\nWhen using slice types, if you are declaring a single value as the default you\ncan use the `default` tag as normal:\n\n```go\ntype Config struct {\n\tHosts []string `env:\"HOSTS,default=localhost\"`\n}\n```\n\nHowever if you want to declare multiple values as the default, you must enclose\nthe values in square brackets:\n\n```go\ntype Config struct {\n\tHosts []string `env:\"HOSTS,default=[localhost,localhost2]`\n}\n```\n\nThis is necessary as the pacakge uses commas as a delimiter to split the struct\ntag options, and without the square brackets it would split the values into\nmultiple tags.\n\n```go\ntype Config struct {\n\tHosts []string `env:\"HOSTS,default=[localhost,localhost2],required\"\n}\n```\n\n### Defaults from Code\n\nYou may define default values also in your code by initializing your struct data\nbefore it's populated by `env.Unmarshal`. However, default values defined as\nstruct tags will take precedence over the ones defined in code.\n\n```go\ntype Config struct {\n    Username string `env:\"USERNAME,default=admin\"`\n    Password string `env:\"PASSWORD\"`\n}\n\ncfg := Config{\n    Username: \"test\",\n    Password: \"password123\",\n}\n\nif err := env.Unmarshal(\u0026cfg); err != nil {\n    log.Fatalf(\"Error unmarshalling config: %v\", err)\n}\n\n// { Username: \"admin\", Password: \"password123\" }\n```\n\n### From file\n\nThe `file` tag option can be used to indicate that the value of the variable\nshould be loaded from a file. The path of the file given by the value of the\nvariable.\n\n```bash\necho \"password123\" \u003e /run/secrets/password\n```\n\n```go\ntype Config struct {\n    Username string `env:\"USERNAME\"`\n    Password string `env:\"PASSWORD,file\"`\n}\n\ncfg := Config{\n    Username: \"test\",\n    Password: \"/run/secrets/password\",\n}\n\nif err := env.Unmarshal(\u0026cfg); err != nil {\n    log.Fatalf(\"Error unmarshalling config: %v\", err)\n}\n\n// { \"Username\": \"test\", \"Password\": \"password123\" }\n```\n\n### Expand variables\n\nThe `expand` tag option can be used to indicate that the value of the variable\nshould be expanded (in either `${var}` or `$var` format) before being set.\n\n```go\ntype Config struct {\n    Username string `env:\"USERNAME,expand\"`\n    Password string `env:\"PASSWORD,expand\"`\n}\n```\n\nThis works great with the `default` tag option:\n\n```go\ntype Config struct {\n    Address string `env:\"ADDRESS,expand,default=${HOST}:${PORT}\"`\n}\n```\n\nWhich results in:\n\n```bash\nHOST=localhost PORT=8080 go run main.go\n{Address:localhost:8080}\n```\n\nAdditionally, default values can be referenced from other struct fields.\nAllowing you to chain default values rather than falling back to an empty value\nwhen an environment variable is not set:\n\n```go\ntype Config struct {\n    Host string `env:\"HOST,default=localhost\"`\n    Port string `env:\"PORT,default=8080\"`\n    Address string `env:\"ADDRESS,expand,default=${HOST}:${PORT}\"`\n}\n```\n\nWhich results in:\n\n```bash\ngo run main.go\n{Host:localhost Port:8080 Address:localhost:8080}\n```\n\n## Contributing\n\nFeel free to open issues or contribute to the project. Contributions are always\nwelcome!\n\n## License\n\nThis project is licensed under the MIT license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsyntaqx%2Fenv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsyntaqx%2Fenv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsyntaqx%2Fenv/lists"}