2
0
config/env.go
2024-10-21 00:15:51 +07:00

163 lines
4.3 KiB
Go

/*
* Copyright (C) 2017 eschao <esc.chao@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config
import (
"fmt"
"io"
"os"
"reflect"
)
// Parse parses given structure interface, extracts environment definitions
// from its tag and sets structure with defined environment variables
func ParseEnv(i interface{}) error {
return ParseEnvWith(i, "")
}
// UsageEnv prints usage description of config i to out
func UsageEnv(out io.Writer, i interface{}) {
// STub
}
// ParseWith parses with given structure interface and environment name prefix
// It is normally used in nested structure.
// For example: we have such structure
// type Database struct {
// Host string `env:"HOST"`
// }
// type Server struct {
// Server string `env:"SERVER"`
// DB Database `env:"DB_"`
// }
//
// The Server.DB.Host will be mapped to environment variable: DB_HOST which is
// concatenated from DB tag in Server struct and Host tag in Database struct
func ParseEnvWith(i interface{}, prefix string) error {
ptrRef := reflect.ValueOf(i)
if ptrRef.IsNil() || ptrRef.Kind() != reflect.Ptr {
return fmt.Errorf("expect a structure pointer type instead of %s",
ptrRef.Kind().String())
}
valueOfStruct := ptrRef.Elem()
if valueOfStruct.Kind() != reflect.Struct {
return fmt.Errorf("expect a structure pointer type instead of %s",
valueOfStruct.Kind().String())
}
return parseValueEnv(valueOfStruct, prefix)
}
// parseValue parses a reflect.Value object
func parseValueEnv(value reflect.Value, prefix string) error {
var err error
typeOfStruct := value.Type()
for i := 0; i < value.NumField() && err == nil; i++ {
valueOfField := value.Field(i)
kindOfField := valueOfField.Kind()
structOfField := typeOfStruct.Field(i)
// Recursively unmarshal if value is ptr type
if kindOfField == reflect.Ptr {
if !valueOfField.IsNil() && valueOfField.CanSet() {
err = ParseEnvWith(valueOfField.Interface(),
prefix+structOfField.Tag.Get("env"))
} else {
continue
}
} else if kindOfField == reflect.Struct {
err = parseValueEnv(valueOfField, prefix+structOfField.Tag.Get("env"))
}
if err != nil {
return err
}
err = setFieldValueEnv(valueOfField, structOfField, prefix)
}
return err
}
// setFieldValue sets a reflect.Value with environment value
func setFieldValueEnv(value reflect.Value, field reflect.StructField, prefix string) error {
envName := field.Tag.Get("env")
if envName == "" {
return nil
}
envValue, ok := os.LookupEnv(prefix + envName)
if !ok {
return nil
}
if !value.CanSet() {
return fmt.Errorf("%s: can't be set", field.Name)
}
var err error
kind := value.Kind()
switch kind {
case reflect.Bool:
err = SetValueWithBool(value, envValue)
case reflect.String:
value.SetString(envValue)
case reflect.Int8:
err = SetValueWithIntX(value, envValue, Int8Size)
case reflect.Int16:
err = SetValueWithIntX(value, envValue, Int16Size)
case reflect.Int, reflect.Int32:
err = SetValueWithIntX(value, envValue, Int32Size)
case reflect.Int64:
err = SetValueWithIntX(value, envValue, Int64Size)
case reflect.Uint8:
err = SetValueWithUintX(value, envValue, Uint8Size)
case reflect.Uint16:
err = SetValueWithUintX(value, envValue, Uint16Size)
case reflect.Uint, reflect.Uint32:
err = SetValueWithUintX(value, envValue, Uint32Size)
case reflect.Uint64:
err = SetValueWithUintX(value, envValue, Uint64Size)
case reflect.Float32:
err = SetValueWithFloatX(value, envValue, Float32Size)
case reflect.Float64:
err = SetValueWithFloatX(value, envValue, Float64Size)
case reflect.Slice:
sp, ok := field.Tag.Lookup("separator")
if !ok {
sp = ":"
}
err = SetValueWithSlice(value, envValue, sp)
default:
return fmt.Errorf("unsupported type: %s", kind.String())
}
if err != nil {
return fmt.Errorf("%s: %s", field.Name, err.Error())
}
return nil
}