{"id":13410764,"url":"https://github.com/ilyakaznacheev/cleanenv","last_synced_at":"2025-05-13T19:05:43.617Z","repository":{"id":37734339,"uuid":"196602978","full_name":"ilyakaznacheev/cleanenv","owner":"ilyakaznacheev","description":"✨Clean and minimalistic environment configuration reader for Golang","archived":false,"fork":false,"pushed_at":"2025-01-05T23:01:57.000Z","size":309,"stargazers_count":1819,"open_issues_count":46,"forks_count":122,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-04-25T18:22:55.509Z","etag":null,"topics":["configuration","environment-configuration","environment-variables","hacktoberfest"],"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/ilyakaznacheev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","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}},"created_at":"2019-07-12T15:28:52.000Z","updated_at":"2025-04-23T15:59:59.000Z","dependencies_parsed_at":"2023-10-17T05:01:29.874Z","dependency_job_id":"729ddcb6-65d0-4191-a927-1db4e0e77dcd","html_url":"https://github.com/ilyakaznacheev/cleanenv","commit_stats":{"total_commits":94,"total_committers":19,"mean_commits":4.947368421052632,"dds":0.3829787234042553,"last_synced_commit":"8ca6c6a9ec7abb855fe656eeab93ed154ca139e3"},"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilyakaznacheev%2Fcleanenv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilyakaznacheev%2Fcleanenv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilyakaznacheev%2Fcleanenv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilyakaznacheev%2Fcleanenv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ilyakaznacheev","download_url":"https://codeload.github.com/ilyakaznacheev/cleanenv/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250869942,"owners_count":21500410,"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":["configuration","environment-configuration","environment-variables","hacktoberfest"],"created_at":"2024-07-30T20:01:09.000Z","updated_at":"2025-04-27T04:47:32.219Z","avatar_url":"https://github.com/ilyakaznacheev.png","language":"Go","funding_links":[],"categories":["Go","Configuration","配置","配置管理 `配置解析库`","配置管理","Uncategorized"],"sub_categories":["Standard CLI","Advanced Console UIs","标准CLI","标准 CLI"],"readme":"![Clean Env](logo.svg)\n\n# Clean Env\n\nMinimalistic configuration reader\n\n[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go) \n[![GoDoc](https://godoc.org/github.com/ilyakaznacheev/cleanenv?status.svg)](https://godoc.org/github.com/ilyakaznacheev/cleanenv)\n[![Go Report Card](https://goreportcard.com/badge/github.com/ilyakaznacheev/cleanenv)](https://goreportcard.com/report/github.com/ilyakaznacheev/cleanenv)\n[![Coverage Status](https://codecov.io/github/ilyakaznacheev/cleanenv/coverage.svg?branch=master)](https://codecov.io/gh/ilyakaznacheev/cleanenv)\n[![Build Status](https://img.shields.io/github/actions/workflow/status/ilyakaznacheev/cleanenv/test.yml)](https://github.com/ilyakaznacheev/cleanenv/actions)\n[![Release](https://img.shields.io/github/release/ilyakaznacheev/cleanenv.svg)](https://github.com/ilyakaznacheev/cleanenv/releases/)\n[![License](https://img.shields.io/github/license/ilyakaznacheev/cleanenv.svg)](https://github.com/ilyakaznacheev/cleanenv/blob/master/LICENSE)\n\n## Overview\n\nThis is a simple configuration reading tool. It just does the following:\n\n- reads and parses configuration structure from the file\n- reads and overwrites configuration structure from environment variables\n- writes a detailed variable list to help output\n\n## Content\n\n- [Installation](#installation)\n- [Usage](#usage)\n    - [Read Configuration](#read-configuration)\n    - [Read Environment Variables Only](#read-environment-variables-only)\n    - [Update Environment Variables](#update-environment-variables)\n    - [Description](#description)\n- [Model Format](#model-format)\n- [Supported types](#supported-types)\n- [Custom Functions](#custom-functions)\n    - [Custom Value Setter](#custom-value-setter)\n    - [Custom Value Update](#custom-value-update)\n- [Supported File Formats](#supported-file-formats)\n- [Integration](#integration)\n    - [Flag](#flag)\n- [Examples](#examples)\n- [Contribution](#contribution)\n- [Thanks](#thanks)\n\n## Installation\n\nTo install the package run\n\n```bash\ngo get -u github.com/ilyakaznacheev/cleanenv\n```\n\n## Usage\n\nThe package is oriented to be simple in use and explicitness.\n\nThe main idea is to use a structured configuration variable instead of any sort of dynamic set of configuration fields like some libraries does, to avoid unnecessary type conversions and move the configuration through the program as a simple structure, not as an object with complex behavior.\n\nThere are just several actions you can do with this tool and probably only things you want to do with your config if your application is not too complicated.\n\n- read configuration file\n- read environment variables\n- read some environment variables again\n\n### Read Configuration\n\nYou can read a configuration file and environment variables in a single function call.\n\n```go\nimport \"github.com/ilyakaznacheev/cleanenv\"\n\ntype ConfigDatabase struct {\n    Port     string `yaml:\"port\" env:\"PORT\" env-default:\"5432\"`\n    Host     string `yaml:\"host\" env:\"HOST\" env-default:\"localhost\"`\n    Name     string `yaml:\"name\" env:\"NAME\" env-default:\"postgres\"`\n    User     string `yaml:\"user\" env:\"USER\" env-default:\"user\"`\n    Password string `yaml:\"password\" env:\"PASSWORD\"`\n}\n\nvar cfg ConfigDatabase\n\nerr := cleanenv.ReadConfig(\"config.yml\", \u0026cfg)\nif err != nil {\n    ...\n}\n```\n\nThis will do the following:\n\n1. parse configuration file according to YAML format (`yaml` tag in this case);\n1. reads environment variables and overwrites values from the file with the values which was found in the environment (`env` tag);\n1. if no value was found on the first two steps, the field will be filled with the default value (`env-default` tag) if it is set.\n\n### Read Environment Variables Only\n\nSometimes you don't want to use configuration files at all, or you may want to use `.env` file format instead. Thus, you can limit yourself with only reading environment variables:\n\n```go \nimport \"github.com/ilyakaznacheev/cleanenv\"\n\ntype ConfigDatabase struct {\n    Port     string `env:\"PORT\" env-default:\"5432\"`\n    Host     string `env:\"HOST\" env-default:\"localhost\"`\n    Name     string `env:\"NAME\" env-default:\"postgres\"`\n    User     string `env:\"USER\" env-default:\"user\"`\n    Password string `env:\"PASSWORD\"`\n}\n\nvar cfg ConfigDatabase\n\nerr := cleanenv.ReadEnv(\u0026cfg)\nif err != nil {\n    ...\n}\n```\n\n### Update Environment Variables\n\nSome environment variables may change during the application run. To get the new values you need to mark these variables as updatable with the tag `env-upd` and then run the update function:\n\n```go\nimport \"github.com/ilyakaznacheev/cleanenv\"\n\ntype ConfigRemote struct {\n    Port     string `env:\"PORT\" env-upd`\n    Host     string `env:\"HOST\" env-upd`\n    UserName string `env:\"USERNAME\"`\n}\n\nvar cfg ConfigRemote\n\ncleanenv.ReadEnv(\u0026cfg)\n\n// ... some actions in-between\n\nerr := cleanenv.UpdateEnv(\u0026cfg)\nif err != nil {\n    ...\n}\n```\n\nHere remote host and port may change in a distributed system architecture. Fields `cfg.Port` and `cfg.Host` can be updated in the runtime from corresponding environment variables. You can update them before the remote service call. Field `cfg.UserName` will not be changed after the initial read, though.\n\n### Description\n\nYou can get descriptions of all environment variables to use them in the help documentation.\n\n```go\nimport \"github.com/ilyakaznacheev/cleanenv\"\n\ntype ConfigServer struct {\n    Port     string `env:\"PORT\" env-description:\"server port\"`\n    Host     string `env:\"HOST\" env-description:\"server host\"`\n}\n\nvar cfg ConfigRemote\n\nhelp, err := cleanenv.GetDescription(\u0026cfg, nil)\nif err != nil {\n    ...\n}\n```\n\nYou will get the following:\n\n```\nEnvironment variables:\n  PORT  server port\n  HOST  server host\n```\n\n## Model Format\n\nLibrary uses tags to configure the model of configuration structure. There are the following tags:\n\n- `env=\"\u003cname\u003e\"` - environment variable name (e.g. `env=\"PORT\"`);\n- `env-upd` - flag to mark a field as updatable. Run `UpdateEnv(\u0026cfg)` to refresh updatable variables from environment;\n- `env-required` - flag to mark a field as required. If set will return an error during environment parsing when the flagged as required field is empty (default Go value). Tag `env-default` is ignored in this case;\n- `env-default=\"\u003cvalue\u003e\"` - default value. If the field wasn't filled from the environment variable default value will be used instead;\n- `env-separator=\"\u003cvalue\u003e\"` - custom list and map separator. If not set, the default separator `,` will be used;\n- `env-description=\"\u003cvalue\u003e\"` - environment variable description;\n- `env-layout=\"\u003cvalue\u003e\"` - parsing layout (for types like `time.Time`);\n- `env-prefix=\"\u003cvalue\u003e\"` - prefix for all fields of nested structure (only for nested structures);\n\n## Supported types\n\nThere are following supported types:\n\n- `int` (any kind);\n- `float` (any kind);\n- `string`;\n- `boolean`;\n- slices (of any other supported type);\n- maps (of any other supported type);\n- `time.Duration`;\n- `time.Time` (layout by default is RFC3339, may be overridden by `env-layout`);\n- `*time.Location` (time zone parsing [depends](https://pkg.go.dev/time#LoadLocation) on running machine);\n- any type that implements `encoding.TextUnmarshaler`;\n- any type implementing `cleanenv.Setter` interface.\n\n\n## Custom Functions\n\nTo enhance package abilities you can use some custom functions.\n\n### Custom Value Setter\n\nTo make custom type allows to set the value from the environment variable, you need to implement the `Setter` interface on the field level:\n\n```go\ntype MyField string\n\nfunc (f *MyField) SetValue(s string) error  {\n    if s == \"\" {\n        return fmt.Errorf(\"field value can't be empty\")\n    }\n    *f = MyField(\"my field is: \"+ s)\n    return nil\n}\n\ntype Config struct {\n    Field MyField `env=\"MY_VALUE\"`\n}\n```\n\n`SetValue` method should implement conversion logic from string to custom type.\n\n### Custom Value Update\n\nYou may need to execute some custom field update logic, e.g. for remote config load.\n\nThus, you need to implement the `Updater` interface on the structure level:\n\n```go\ntype Config struct {\n    Field string\n}\n\nfunc (c *Config) Update() error {\n    newField, err := SomeCustomUpdate()\n    f.Field = newField\n    return err\n}\n```\n\n## Supported File Formats\n\nThere are several most popular config file formats supported:\n\n- YAML (`.yaml`, `.yml`)\n- JSON (`.json`)\n- TOML (`.toml`)\n- EDN (`.edn`)\n- ENV (`.env`)\n\n**Note**:\n- while using `.env` file the library will set corresponding data to process environment variables.\n  It will override existing variables with the same keys in the process environment.\n\n## Integration\n\nThe package can be used with many other solutions. To make it more useful, we made some helpers.\n\n### Flag\n\nYou can use the cleanenv help together with Golang `flag` package.\n\n```go\n// create some config structure\nvar cfg config \n\n// create flag set using `flag` package\nfset := flag.NewFlagSet(\"Example\", flag.ContinueOnError)\n\n// get config usage with wrapped flag usage\nfset.Usage = cleanenv.FUsage(fset.Output(), \u0026cfg, nil, fset.Usage)\n\nfset.Parse(os.Args[1:])\n```\n\n## Examples\n\n```go\ntype Config struct {\n    Port string `yaml:\"port\" env:\"PORT\" env-default:\"8080\"`\n    Host string `yaml:\"host\" env:\"HOST\" env-default:\"localhost\"`\n}\n\nvar cfg Config\n\nerr := ReadConfig(\"config.yml\", \u0026cfg)\nif err != nil {\n    ...\n}\n```\n\nThis code will try to read and parse the configuration file `config.yml` as the structure is described in the `Config` structure. Then it will overwrite fields from available environment variables (`PORT`, `HOST`).\n\nFor more details check the [example](/example) directory.\n\n## Version Support Policy\n\nWe support the last 7 versions of Golang. E.g. if the current version is 1.19, we test compatibility with all versions from 1.19 to 1.13.\n\nIf you use an older version of Golang in your project, please use an older library version.\n\n## Contribution\n\nThe tool is open-sourced under the [MIT](LICENSE) license.\n\nIf you find some error, want to add something or ask a question - feel free to create an issue and/or make a pull request.\n\nGuidelines for contribution may be found in [CONTRIBUTING.md](CONTRIBUTING.md).\n\nAny contribution is welcome.\n\n## Thanks\n\nBig thanks to a project [kelseyhightower/envconfig](https://github.com/kelseyhightower/envconfig) for inspiration.\n\nThe logo was made by [alexchoffy](https://www.instagram.com/alexchoffy/).\n\n## Blog Posts\n\n[Clean Configuration Management in Golang](https://dev.to/ilyakaznacheev/clean-configuration-management-in-golang-1c89).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filyakaznacheev%2Fcleanenv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Filyakaznacheev%2Fcleanenv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filyakaznacheev%2Fcleanenv/lists"}