Skip to content

Commit

Permalink
Improve the default values for int based environment vars
Browse files Browse the repository at this point in the history
  • Loading branch information
wolfeidau committed Jun 5, 2024
1 parent c3e9a57 commit b15f7a2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 10 deletions.
20 changes: 10 additions & 10 deletions lambda/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,20 +95,12 @@ func Handler(ctx context.Context, evt json.RawMessage) (string, error) {
queues = strings.Split(queue, ",")
}

if timeout == "" {
timeout = "15"
}

if maxIdleConns == "" {
maxIdleConns = "100" // Default to 100 in line with http.DefaultTransport
}

configuredTimeout, err := strconv.Atoi(timeout)
configuredTimeout, err := toIntWithDefault(timeout, 15)
if err != nil {
return "", err
}

configuredMaxIdleConns, err := strconv.Atoi(maxIdleConns)
configuredMaxIdleConns, err := toIntWithDefault(maxIdleConns, 100)
if err != nil {
return "", err
}
Expand Down Expand Up @@ -283,3 +275,11 @@ func checkMutuallyExclusiveEnvVars(varNames ...string) error {
return fmt.Errorf("the environment variables [%s] are mutually exclusive", strings.Join(foundVars, ","))
}
}

func toIntWithDefault(val string, defaultVal int) (int, error) {
if val == "" {
return defaultVal, nil
}

return strconv.Atoi(val)
}
43 changes: 43 additions & 0 deletions lambda/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import "testing"

func Test_toIntWithDefault(t *testing.T) {
type args struct {
value string
defaults int
}
tests := []struct {
name string
args args
want int
wantErr bool
}{
{
name: "empty",
args: args{value: "", defaults: 10},
want: 10,
},
{
name: "invalid",
args: args{value: "invalid", defaults: 10},
wantErr: true,
},
{
name: "valid",
args: args{value: "20", defaults: 10},
want: 20,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got, err := toIntWithDefault(tt.args.value, tt.args.defaults); (err != nil) != tt.wantErr {
t.Errorf("toIntWithDefault() error = %v, wantErr %v", err, tt.wantErr)
} else {
if got != tt.want {
t.Errorf("toIntWithDefault() = %v, want %v", got, tt.want)
}
}
})
}
}

0 comments on commit b15f7a2

Please sign in to comment.