{"id":13410809,"url":"https://github.com/BoRuDar/configuration","last_synced_at":"2025-03-14T16:33:01.397Z","repository":{"id":39915381,"uuid":"224488441","full_name":"BoRuDar/configuration","owner":"BoRuDar","description":"Library for setting values to structs' fields from env, flags, files or default tag","archived":false,"fork":false,"pushed_at":"2024-04-13T22:05:48.000Z","size":130,"stargazers_count":109,"open_issues_count":0,"forks_count":10,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-07-31T20:44:00.484Z","etag":null,"topics":["12-factor","config","configuration","configuration-management","go","golang","microservices","reflect","reflection"],"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/BoRuDar.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-11-27T17:58:49.000Z","updated_at":"2024-07-09T09:44:53.000Z","dependencies_parsed_at":"2024-01-08T14:30:54.243Z","dependency_job_id":"14442ac5-669b-4c18-a900-240d9c22283a","html_url":"https://github.com/BoRuDar/configuration","commit_stats":null,"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BoRuDar%2Fconfiguration","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BoRuDar%2Fconfiguration/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BoRuDar%2Fconfiguration/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BoRuDar%2Fconfiguration/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BoRuDar","download_url":"https://codeload.github.com/BoRuDar/configuration/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243610456,"owners_count":20318966,"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":["12-factor","config","configuration","configuration-management","go","golang","microservices","reflect","reflection"],"created_at":"2024-07-30T20:01:09.435Z","updated_at":"2025-03-14T16:33:01.381Z","avatar_url":"https://github.com/BoRuDar.png","language":"Go","readme":"[![Go Report Card](https://goreportcard.com/badge/github.com/BoRuDar/configuration/v4)](https://goreportcard.com/report/github.com/BoRuDar/configuration/v4)\n[![codecov](https://codecov.io/gh/BoRuDar/configuration/branch/master/graph/badge.svg)](https://codecov.io/gh/BoRuDar/configuration)\n[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/6295/badge)](https://www.bestpractices.dev/projects/6295)\n[![GoDoc](https://godoc.org/github.com/BoRuDar/configuration?status.png)](https://godoc.org/github.com/BoRuDar/configuration/v4)\n[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)\n[BuyMeACoffee](https://www.buymeacoffee.com/borudar)\n\n\n# Configuration\nis a library for injecting values recursively into structs - a convenient way of setting up a configuration object.\nAvailable features:\n- setting *default* values for struct fields - `NewDefaultProvider()`\n- setting values from *environment* variables - `NewEnvProvider()`\n- setting values from command line *flags* - `NewFlagProvider()`\n- setting values from a JSON *file* - `NewJSONFileProvider(\"./testdata/input.json\")`\n\n## Supported types:\n- `string`, `*string`, `[]string`, `[]*string`\n- `bool`, `*bool`, `[]bool`, `[]*bool`\n- `int`, `int8`, `int16`, `int32`, `int64` + slices of these types\n- `*int`, `*int8`, `*int16`, `*int32`, `*int64` + slices of these types\n- `uint`, `uint8`, `uint16`, `uint32`, `uint64` + slices of these types\n- `*uint`, `*uint8`, `*uint16`, `*uint32`, `*uint64` + slices of these types\n- `float32`, `float64` + slices of these types\n- `*float32`, `*float64` + slices of these types\n- `time.Duration` from strings like `12ms`, `2s` etc.\n- embedded structs and pointers to structs\n- any custom type which satisfies `FieldSetter` [interface](#FieldSetter-interface)\n\n\n# Why?\n- your entire configuration can be defined in one model\n- all metadata is in your model (defined with `tags`)\n- easy to set/change a source of data for your configuration\n- easy to set a priority of sources to fetch data from (e.g., 1.`flags`, 2.`env`, 3.`default` or another order)\n- you can implement your custom provider\n- no external dependencies\n- complies with `12-factor app`\n\n\n# Quick start\nImport path `github.com/BoRuDar/configuration/v5`\n```go\n// defining a struct\ntype Conf struct {\n    Name     string `flag:\"name\"`\n    LastName string `default:\"defaultLastName\"`\n    Age      byte   `env:\"AGE_ENV\"               default:\"-1\"`\n    BoolPtr  *bool  `default:\"false\"`\n    ObjPtr   *struct {\n        F32       float32       `default:\"32\"`\n        StrPtr    *string       `default:\"str_ptr_test\"`\n        HundredMS time.Duration `default:\"100ms\"` // nolint:stylecheck\n    }\n    Obj struct {\n        IntPtr     *int16   `default:\"123\"`\n        Beta       int      `file_json:\"inside.beta\"   default:\"24\"`\n        StrSlice   []string `default:\"one;two\"`\n        IntSlice   []int64  `default:\"3; 4\"`\n        unexported string   // ignored\n    }\n    URLs   []*string `default:\"http://localhost:3000;1.2.3.4:8080\"`\n    HostIP ipTest    `default:\"127.0.0.3\"`\n}\n\ncfg, err := New[Conf](  // specify the [T] of the structure to be returned\n    // order of execution will be preserved:\n    NewFlagProvider(),             // 1st\n    NewEnvProvider(),              // 2nd\n    NewJSONFileProvider(fileName), // 3rd\n    NewDefaultProvider(),          // 4th\n)\nif err != nil {\n    t.Fatalf(\"unexpected error: %v\", err)\n}\n```\n\nIf you need only ENV variables and default values you can use a shorter form:\n```go\ncfg, err := configuration.FromEnvAndDefault[T]()\n```\n\n\n# Providers\nYou can specify one or more providers. They will be executed in order of definition:\n```go\n[]Provider{\n    NewFlagProvider(),     // 1\n    NewEnvProvider(),      // 2\n    NewDefaultProvider(),  // 3\n} \n```\n**IMPORTANT:** If provider sets value successfully next ones will **NOT** be executed \n(if flag provider from the sample above finds the value - then the env and default providers are skipped). \nThe value of the first successfully executed provider will be set.\nIf none of providers can set value - an error will be returned.\n\n\n### Custom provider\nYou can define a custom provider which should satisfy this interface:\n```go\ntype Provider interface {\n    Name() string\n    Tag() string\n    Init(ptr any) error\n    Provide(field reflect.StructField, v reflect.Value) error\n}\n```\n\n### Default provider\nLooks for `default` tag and set value from it:\n```go\nstruct {\n    // ...\n    Name string `default:\"defaultName\"`\n    // ...\n}\n```\nSo `Name` will be set to \"defaultName\".\n\n\n### Env provider\nLooks for `env` tag and tries to find an ENV variable with the name from the tag (`AGE` in this example):\n```go\nstruct {\n    // ...\n    Age      byte   `env:\"AGE\"`\n    // ...\n}\n```\nName inside tag `env:\"\u003cname\u003e\"` must be unique for each field. \nOnly strings in **UPPER** register for ENV vars are accepted:\n```bash\nbad_env_var_name=bad\nAlso_Bad_Env_Var_Name=bad\nGOOD_ENV_VAR_NAME=good\n```\n\n\n### Flag provider\nLooks for `flag` tag and tries to set the value from the command line flag `-first_name`\n```go\nstruct {\n    // ...\n    Name     string `flag:\"first_name|default_value|Description\"`\n    // ...\n}\n```\nName inside tag `flag:\"\u003cname\u003e\"` must be unique for each field.\n`default_value` and `description` sections are `optional` and may be omitted.\n\n*Note*: if program is executed with `-help` or `-h` flag you will see all available flags with description:\n```bash\nFlags: \n\t-first_name\t\t\"Description (default: default_value)\"\n``` \nAnd program execution will be terminated.\n#### Options for _NewFlagProvider_\n* `WithFlagSet(s FlagSet)`  - sets a custom `FlagSet`\n\n\n### JSON File provider \nRequires `file_json:\"\u003cpath_to_json_field\u003e\"` tag.\n```go\nNewJSONFileProvider(\"./testdata/input.json\")\n```\nFor example, tag `file_json:\"cache.retention\"` will assume that you have this structure of your JSON file:\n```json\n{\n  \"cache\": {\n    \"retention\": 1\n  }\n}\n```\n\n### Additional providers\n* [YAML files](https://github.com/BoRuDar/configuration-yaml-file)\n\n\n## FieldSetter interface\nYou can define how to set fields with any custom types: \n```go\ntype FieldSetter interface {\n\tSetField(field reflect.StructField, val reflect.Value, valStr string) error\n}\n```\nExample:\n```go\ntype ipTest net.IP\n\nfunc (it *ipTest) SetField(_ reflect.StructField, val reflect.Value, valStr string) error {\n\ti := ipTest(net.ParseIP(valStr))\n\n\tif val.Kind() == reflect.Pointer {\n\t\tval.Set(reflect.ValueOf(\u0026i))\n\t} else {\n\t\tval.Set(reflect.ValueOf(i))\n\t}\n\n\treturn nil\n}\n```\n\n\n# Contribution\n1. Open a feature request or a bug report in [issues](https://github.com/BoRuDar/configuration/issues)\n2. Fork and create a PR into `dev` branch\n","funding_links":["https://www.buymeacoffee.com/borudar"],"categories":["Configuration","Uncategorized","配置","配置管理","配置管理 `配置解析库`"],"sub_categories":["Standard CLI","标准CLI","Advanced Console UIs","标准 CLI"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBoRuDar%2Fconfiguration","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBoRuDar%2Fconfiguration","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBoRuDar%2Fconfiguration/lists"}