Select Git revision
utils.go 5.50 KiB
package utils
import (
"bytes"
"github.com/mohae/deepcopy"
"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/errors"
"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/string_utils"
"net/mail"
"net/url"
"os"
"reflect"
"regexp"
"strings"
)
// GetEnv is a helper function for getting environment variables with a default
func GetEnv(name string, def string) (env string) {
// If variable not set, provide default
if env = os.Getenv(name); env == "" {
env = def
}
return
}
// CorsHeaders returns a map to allow Cors
func CorsHeaders() map[string]string {
return map[string]string{
"Access-Control-Allow-Origin": "*",
// do not wildcard: https://stackoverflow.com/questions/13146892/cors-access-control-allow-headers-wildcard-being-ignored
"Access-Control-Allow-Headers": "authorization, content-type, referer, sec-ch-ua, sec-ch-ua-mobile, sec-ch-ua-platform, user-agent, x-amz-date, x-amz-security-token",
"Access-Control-Allow-Methods": "OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD",
"Access-Control-Max-Age": "86400",
"Access-Control-Allow-Credentials": "true",
}
}
func DeepCopy(fromValue interface{}) (toValue interface{}) {
return deepcopy.Copy(fromValue)
}
func ValueToPointer[V any](value V) *V {
return &value
}
func PointerToValue[V any](value *V) V {
if value != nil {
return *value
}
return *new(V) // zero value of V
}
func ValidateEmailAddress(email string) (string, error) {
if email == "" {
return "", errors.Error("email address is empty")
}
cleanEmail := strings.ToLower(strings.TrimSpace(email))
cleanEmail = string_utils.RemoveAllWhiteSpaces(cleanEmail)
// We validate it but still return it since in some cases we don't want to break everything if the email is bad
_, err := mail.ParseAddress(cleanEmail)
if err != nil {
return cleanEmail, errors.Wrap(err, "could not parse email address")
}
return cleanEmail, nil
}
func StripEmail(email string) (strippedEmail string, strippedDomain string) {