Skip to content

Commit

Permalink
initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
qiangxue committed Dec 9, 2019
0 parents commit f865720
Show file tree
Hide file tree
Showing 9 changed files with 778 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/
17 changes: 17 additions & 0 deletions .travis
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
dist: bionic

language: go

go:
- 1.13.x

install:
- go get golang.org/x/tools/cmd/cover
- go get github.com/mattn/goveralls
- go get golang.org/x/lint/golint

script:
- test -z "`gofmt -l -d .`"
- test -z "`golint ./...`"
- go test -v -covermode=count -coverprofile=coverage.out
- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Qiang Xue

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
135 changes: 135 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# go-env

[![GoDoc](https://godoc.org/github.com/qiangxue/go-env?status.png)](http://godoc.org/github.com/qiangxue/go-env)
[![Build Status](https://travis-ci.org/qiangxue/go-env.svg?branch=master)](https://travis-ci.org/qiangxue/go-env)
[![Coverage Status](https://coveralls.io/repos/github/qiangxue/go-env/badge.svg?branch=master)](https://coveralls.io/github/qiangxue/go-env?branch=master)
[![Go Report](https://goreportcard.com/badge/github.com/qiangxue/go-env)](https://goreportcard.com/report/github.com/qiangxue/go-env)

## Description

go-env is a Go library that can populate a struct with environment variable values. A common use of go-env is
to load a configuration struct with values set in the environment variables.

## Requirements

Go 1.13 or above.


## Getting Started

### Installation

Run the following command to install the package:

```
go get github.com/qiangxue/go-env
```

### Loading From Environment Variables

The easiest way of using go-env is to call `env.Load()`, like the following:

```go
package main

import (
"fmt"
"github.com/qiangxue/go-env"
"os"
)

type Config struct {
Host string
Port int
}

func main() {
_ = os.Setenv("APP_HOST", "127.0.0.1")
_ = os.Setenv("APP_PORT", "8080")

var cfg Config
if err := env.Load(&cfg); err != nil {
panic(err)
}
fmt.Println(cfg.Host)
fmt.Println(cfg.Port)
// Output:
// 127.0.0.1
// 8080
}
```

### Environment Variable Names

When go-env populates a struct from environment variables, it uses the following rules to match
a struct field with an environment variable:
- Only public struct fields will be populated
- If the field has an `env` tag, use the tag value as the name, unless the tag value is `-` in which case it means
the field should NOT be populated.
- If the field has no `env` tag, turn the field name into snake format and use that as the name. For example,
a field name `HostName` will be turned into `Host_Name`, and `MyURL` becomes `My_URL`.
- Names are turned into upper case and prefixed with the specified prefix when they are used to look up
in the environment variables.

By default, prefix `APP_` will be used. You can customize the prefix by using `env.New()` to create
a customized loader. For example,

```go
package main

import (
"fmt"
"github.com/qiangxue/go-env"
"log"
"os"
)

type Config struct {
Host string `env:"ES_HOST"`
Port int `env:"ES_PORT"`
Password string `env:"ES_PASSWORD,secret"`
}

func main() {
_ = os.Setenv("API_HOST", "127.0.0.1")
_ = os.Setenv("API_PORT", "8080")
_ = os.Setenv("API_PASSWORD", "test")

var cfg Config
loader := env.New("API_", log.Printf)
if err := loader.Load(&cfg); err != nil {
panic(err)
}
fmt.Println(cfg.Host)
fmt.Println(cfg.Port)
fmt.Println(cfg.Password)
// Output:
// 127.0.0.1
// 8080
// test
}
```

In the above code, the `Password` field is tagged as `secret`. The log function respects this flag by masking
the field value when logging it in order not to reveal sensitive information.

By setting the prefix to an empty string, you can disable the name prefix completely.


### Data Parsing Rules

Because the values of environment variables are strings, if the corresponding struct fields are of different types,
go-env will convert the string values into appropriate types before assigning them to the struct fields.

- If a struct contains embedded structs, the fields of the embedded structs will be populated like they are directly
under the containing struct.

- If a struct field type implements `env.Setter`, `env.TextMarshaler`, or `env.BinaryMarshaler` interface,
the corresponding interface method will be used to load a string value into the field.

- If a struct field is of a primary type, such as `int`, `string`, `bool`, etc., a string value will be parsed
accordingly and assigned to the field. For example, the string value `TRUE` can be parsed correctly into a
boolean `true` value, while `TrUE` will cause a parsing error.

- If a struct field is of a complex type, such as map, slice, struct, the string value will be treated as a JSON
string, and `json.Unmarshal()` will be called to populate the struct field from the JSON string.
Loading

0 comments on commit f865720

Please sign in to comment.