diff options
| -rw-r--r-- | .github/workflows/test.yml | 27 | ||||
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | README.md | 3 | ||||
| -rw-r--r-- | doc.go | 3 | ||||
| -rw-r--r-- | env.go | 72 | ||||
| -rw-r--r-- | env_test.go | 123 | ||||
| -rw-r--r-- | go.mod | 4 | ||||
| -rw-r--r-- | go.sum | 4 |
8 files changed, 239 insertions, 0 deletions
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7dabf09 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,27 @@ +name: Test + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + run-tests: + runs-on: ubuntu-22.04 + steps: + - name: Checkout code + uses: actions/checkout@v4 + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.23' + - name: Runs tests with coverage + run: go test -race -coverprofile=coverage.out -covermode=atomic ./... + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v4 + with: + files: coverage.out + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3cc2e17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.git +/tags + diff --git a/README.md b/README.md new file mode 100644 index 0000000..ed46d3b --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Envelope + + @@ -0,0 +1,3 @@ +// Envelope is a library designed to enable easily populating a Go struct +// based on environment variables. +package envelope @@ -0,0 +1,72 @@ +package envelope + +import ( + "fmt" + "os" + "reflect" + "strconv" +) + +func LoadFromEnv(ptr interface{}) error { + v := reflect.ValueOf(ptr) + if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + return fmt.Errorf("ptr must be a pointer to a struct") + } + v = v.Elem() + t := v.Type() + + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + fieldValue := v.Field(i) + + envName := field.Tag.Get("env") + if envName == "" { + continue // Skip if the tag isn't set. + } + + envValue := os.Getenv(envName) + if envValue == "" { + continue // Skip if the environment variable is not set. + } + + if err := setFieldValue(fieldValue, envValue); err != nil { + return fmt.Errorf("error while setting field %s from environment variable %s: %w", field.Name, envName, err) + } + } + + return nil +} + +func setFieldValue(field reflect.Value, value string) error { + switch field.Kind() { + case reflect.String: + field.SetString(value) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + intValue, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return fmt.Errorf("unable to parse %s as an integer: %w", value, err) + } + field.SetInt(intValue) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + uintValue, err := strconv.ParseUint(value, 10, 64) + if err != nil { + return fmt.Errorf("unable to parse %s as an unsigned integer: %w", value, err) + } + field.SetUint(uintValue) + case reflect.Bool: + boolValue, err := strconv.ParseBool(value) + if err != nil { + return fmt.Errorf("unable to parse %s as an boolean: %w", value, err) + } + field.SetBool(boolValue) + case reflect.Float32, reflect.Float64: + floatValue, err := strconv.ParseFloat(value, 64) + if err != nil { + return fmt.Errorf("unable to parse %s as an float: %w", value, err) + } + field.SetFloat(floatValue) + default: + return fmt.Errorf("unsupported field type: %s", field.Kind()) + } + return nil +} diff --git a/env_test.go b/env_test.go new file mode 100644 index 0000000..4009b59 --- /dev/null +++ b/env_test.go @@ -0,0 +1,123 @@ +package envelope + +import ( + "os" + "testing" + "time" + + "github.com/eugenetriguba/checkmate/assert" + "github.com/eugenetriguba/checkmate/check" +) + +type TestStruct struct { + String string `env:"TEST_STRING"` + Int int `env:"TEST_INT"` + Uint uint `env:"TEST_UINT"` + Bool bool `env:"TEST_BOOL"` + Float float64 `env:"TEST_FLOAT"` + Untagged string + Unexported string `env:"TEST_UNEXPORTED"` +} + +func TestLoadFromEnv(t *testing.T) { + os.Setenv("TEST_STRING", "hello") + os.Setenv("TEST_INT", "-42") + os.Setenv("TEST_UINT", "42") + os.Setenv("TEST_BOOL", "true") + os.Setenv("TEST_FLOAT", "3.14") + + defer func() { + os.Unsetenv("TEST_STRING") + os.Unsetenv("TEST_INT") + os.Unsetenv("TEST_UINT") + os.Unsetenv("TEST_BOOL") + os.Unsetenv("TEST_FLOAT") + os.Unsetenv("TEST_UNEXPORTED") + }() + + var ts TestStruct + err := LoadFromEnv(&ts) + + check.Nil(t, err) + check.Equal(t, ts.String, "hello") + check.Equal(t, ts.Int, -42) + check.Equal(t, ts.Uint, uint(42)) + check.True(t, ts.Bool) + check.Equal(t, ts.Float, 3.14) + check.Equal(t, ts.Untagged, "") + check.Equal(t, ts.Unexported, "") +} + +func TestLoadFromEnvErrors(t *testing.T) { + tests := []struct { + name string + input interface{} + envVars map[string]string + expectedErr string + }{ + { + name: "Non-pointer input", + input: TestStruct{}, + expectedErr: "ptr must be a pointer to a struct", + }, + { + name: "Pointer to non-struct", + input: new(string), + expectedErr: "ptr must be a pointer to a struct", + }, + { + name: "Invalid int", + input: &struct { + Int int `env:"TEST_INT"` + }{}, + envVars: map[string]string{"TEST_INT": "not an int"}, + expectedErr: "error while setting field Int from environment variable TEST_INT", + }, + { + name: "Invalid uint", + input: &struct { + Uint uint `env:"TEST_UINT"` + }{}, + envVars: map[string]string{"TEST_UINT": "-42"}, + expectedErr: "error while setting field Uint from environment variable TEST_UINT", + }, + { + name: "Invalid bool", + input: &struct { + Bool bool `env:"TEST_BOOL"` + }{}, + envVars: map[string]string{"TEST_BOOL": "not a bool"}, + expectedErr: "error while setting field Bool from environment variable TEST_BOOL", + }, + { + name: "Invalid float", + input: &struct { + Float float64 `env:"TEST_FLOAT"` + }{}, + envVars: map[string]string{"TEST_FLOAT": "not a float"}, + expectedErr: "error while setting field Float from environment variable TEST_FLOAT", + }, + { + name: "Unsupported type", + input: &struct { + Unsupported time.Time `env:"TEST_UNSUPPORTED"` + }{}, + envVars: map[string]string{"TEST_UNSUPPORTED": "2023-08-31T12:34:56Z"}, + expectedErr: "error while setting field Unsupported from environment variable TEST_UNSUPPORTED", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + for k, v := range tt.envVars { + os.Setenv(k, v) + defer os.Unsetenv(k) + } + + err := LoadFromEnv(tt.input) + + assert.NotNil(t, err) + assert.ErrorContains(t, err, tt.expectedErr) + }) + } +} @@ -1,3 +1,7 @@ module github.com/eugenetriguba/envelope go 1.23.0 + +require github.com/eugenetriguba/checkmate v0.3.2 + +require github.com/google/go-cmp v0.6.0 // indirect @@ -0,0 +1,4 @@ +github.com/eugenetriguba/checkmate v0.3.2 h1:vcALwpLLpt0FBxckjuobNFYtBLtlCT2p55Xk4p0SAhk= +github.com/eugenetriguba/checkmate v0.3.2/go.mod h1:IY38Cl4zlNI1dg+wcDYwrbWZfJ9i2/ouWf8C0N8c/do= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= |