Matrix/convert.go

58 lines
1.3 KiB
Go

package main
import (
"errors"
"os"
"strconv"
)
func getEnvFallback(key string, fallback ...string) (string, error) {
// Check for function fallback signature
length := len(fallback)
if length > 1 {
return "", errors.New("Invalid signature: Too many fallback values provided!")
}
// Try to get environment variable
value, exists := os.LookupEnv(key)
if exists {
return value, nil
}
// Try using fallback value instead
if length == 1 {
return fallback[0], nil
} else if length == 0 {
// No fallback value provided
return "", errors.New("Panic: No fallback value provided!")
}
// Could not get environment variable
return "", errors.New("Could not get environment variable: " + key)
}
func convertFallback(input string, fallback ...int) (int, error) {
// Check for function fallback signature
length := len(fallback)
if length > 1 {
return 0, errors.New("Invalid signature: Too many fallback values provided!")
}
// Try to convert input to int
value, err := strconv.Atoi(input)
if err == nil {
return value, nil
}
// Try using fallback value instead
if length == 1 {
return fallback[0], nil
} else if length == 0 {
// No fallback value provided
return 0, errors.New("Panic: No fallback value provided!")
}
// Could not convert input
return 0, err
}