From c017a559c7b33944ce7cd38deccacab4fd61d0b7 Mon Sep 17 00:00:00 2001 From: Ross Tannenbaum Date: Fri, 13 Oct 2023 09:47:50 -0700 Subject: [PATCH] chore: allow integer env vars (#1289) --- pkg/env/integersetting.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 pkg/env/integersetting.go diff --git a/pkg/env/integersetting.go b/pkg/env/integersetting.go new file mode 100644 index 000000000..2ea0f1bdf --- /dev/null +++ b/pkg/env/integersetting.go @@ -0,0 +1,33 @@ +package env + +import ( + "strconv" +) + +// IntegerSetting represents an environment variable which should be parsed into an integer. +type IntegerSetting interface { + Setting + Int() int +} + +type integerSetting struct { + Setting + defaultValue int +} + +// Int returns the int object represented by the environment variable. +func (s *integerSetting) Int() int { + v, err := strconv.Atoi(s.Value()) + if err != nil { + return s.defaultValue + } + return v +} + +// RegisterIntegerSetting globally registers and returns a new integer setting. +func RegisterIntegerSetting(envVar string, defaultValue int, opts ...SettingOption) IntegerSetting { + return &integerSetting{ + Setting: RegisterSetting(envVar, append(opts, WithDefault(strconv.Itoa(defaultValue)))...), + defaultValue: defaultValue, + } +}