Skip to content
Snippets Groups Projects
Select Git revision
  • bf093221e6df5fbe4ba353ed1b705e915e7ad118
  • main default protected
  • v1.302.0
  • v1.301.0
  • v1.300.0
  • v1.299.0
  • v1.298.0
  • v1.297.0
  • v1.296.0
  • v1.295.0
  • v1.294.0
  • v1.293.0
  • v1.292.0
  • v1.291.0
  • v1.290.0
  • v1.289.0
  • v1.288.0
  • v1.287.0
  • v1.286.0
  • v1.285.0
  • v1.284.0
  • v1.283.0
22 results

utils.go

Blame
  • 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) {