♻️ Use uint8 for Env
This commit is contained in:
parent
d7de194a90
commit
917f919401
6 changed files with 135 additions and 21 deletions
|
|
@ -1,12 +1,20 @@
|
|||
package config
|
||||
|
||||
type Env string
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:generate stringer -type Env
|
||||
|
||||
type Env uint8
|
||||
|
||||
const (
|
||||
Dev Env = "dev"
|
||||
Prod Env = "prod"
|
||||
Qa Env = "qa"
|
||||
Test Env = "test"
|
||||
Dev Env = iota + 1
|
||||
Prod
|
||||
Qa
|
||||
Test
|
||||
)
|
||||
|
||||
var Envs = [...]Env{
|
||||
|
|
@ -16,6 +24,28 @@ var Envs = [...]Env{
|
|||
Test,
|
||||
}
|
||||
|
||||
func (e Env) MarshalText() ([]byte, error) {
|
||||
return []byte(e.String()), nil
|
||||
}
|
||||
|
||||
var ErrEnvUnmarshal = errors.New("unable to unmarshal value")
|
||||
|
||||
func (e *Env) UnmarshalText(text []byte) error {
|
||||
if e == nil {
|
||||
return fmt.Errorf("%w: nil pointer", ErrEnvUnmarshal)
|
||||
}
|
||||
|
||||
val := strings.ToUpper(string(text))
|
||||
|
||||
for _, ee := range Envs {
|
||||
if val == strings.ToUpper(ee.String()) {
|
||||
*e = ee
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%w: invalid value: %s", ErrEnvUnmarshal, text)
|
||||
}
|
||||
|
||||
func ValidEnvOrDev(e Env) Env {
|
||||
if ValidEnv(e) {
|
||||
return e
|
||||
|
|
@ -31,7 +61,3 @@ func ValidEnv(env Env) bool {
|
|||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (e Env) String() string {
|
||||
return string(e)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue