78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package environment
|
|
|
|
import (
|
|
"encoding/json"
|
|
"strings"
|
|
|
|
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
|
|
)
|
|
|
|
type ApplicationEnvironment string
|
|
|
|
const (
|
|
ApplicationEnvironmentUndefined ApplicationEnvironment = "undefined"
|
|
ApplicationEnvironmentDev ApplicationEnvironment = "dev"
|
|
ApplicationEnvironmentProd ApplicationEnvironment = "prod"
|
|
)
|
|
|
|
var allowedEnvironments = map[ApplicationEnvironment]struct{}{
|
|
ApplicationEnvironmentUndefined: {},
|
|
ApplicationEnvironmentDev: {},
|
|
ApplicationEnvironmentProd: {},
|
|
}
|
|
|
|
func ParseEnvironment(value string) ApplicationEnvironment {
|
|
s := ApplicationEnvironment(strings.ToLower(value))
|
|
if !s.IsValid() {
|
|
return ApplicationEnvironmentUndefined
|
|
}
|
|
return s
|
|
}
|
|
|
|
func ParseAndValidateEnvironment(status string) (ApplicationEnvironment, error) {
|
|
parsed := ParseEnvironment(status)
|
|
if _, ok := allowedEnvironments[parsed]; ok {
|
|
return parsed, nil
|
|
}
|
|
return ApplicationEnvironmentUndefined, types.ErrUnsupportedApplicationEnvironment
|
|
}
|
|
|
|
func (t ApplicationEnvironment) String() string {
|
|
return string(t)
|
|
}
|
|
|
|
func (t ApplicationEnvironment) Validate() error {
|
|
if _, ok := allowedEnvironments[t]; ok {
|
|
return nil
|
|
}
|
|
return types.ErrUnsupportedApplicationEnvironment
|
|
}
|
|
|
|
func (t ApplicationEnvironment) IsValid() bool {
|
|
_, ok := allowedEnvironments[t]
|
|
return ok
|
|
}
|
|
|
|
func (t ApplicationEnvironment) MarshalJSON() ([]byte, error) {
|
|
if err := t.Validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return json.Marshal(t.String())
|
|
}
|
|
|
|
func (t *ApplicationEnvironment) UnmarshalJSON(data []byte) error {
|
|
if t == nil {
|
|
return types.ErrUnmarshalApplicationEnvironmentIntoNilPointer
|
|
}
|
|
var value string
|
|
if err := json.Unmarshal(data, &value); err != nil {
|
|
return err
|
|
}
|
|
parsed := ParseEnvironment(value)
|
|
if err := parsed.Validate(); err != nil {
|
|
return err
|
|
}
|
|
*t = parsed
|
|
return nil
|
|
}
|