Skip to content

Instantly share code, notes, and snippets.

@TJM
Created September 1, 2021 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TJM/fdbd22b7ef4d4e7f3841f0fec78ba817 to your computer and use it in GitHub Desktop.
Save TJM/fdbd22b7ef4d4e7f3841f0fec78ba817 to your computer and use it in GitHub Desktop.
REALLY basic idea to convert a submitted string value to an appropriate type (interface{}) to match a Puppet Type
// getInterfaceValue will return an interface{} with an appropriate type for the puppetType
// NOTE: This is *very* basic and will revert to just returning the string value by default.
func getInterfaceValue(puppetType string, val string) (retVal interface{}) {
var err error
if val == "" {
return nil // Don't set a parameter that is "" (empty)
}
// Handle Optional[WHATEVER]
if strings.HasPrefix(puppetType, "Optional[") {
puppetType = strings.TrimPrefix(puppetType, "Optional[")
puppetType = strings.TrimSuffix(puppetType, "]")
return getInterfaceValue(puppetType, val)
}
if puppetType == "Integer" {
retVal, err = strconv.Atoi(val)
if err != nil {
log.WithField("val", val).Error("Error converting to integer: ", err)
return nil
}
return
}
if puppetType == "Boolean" {
switch val {
case "yes", "true", "1":
return true
default:
return false
}
}
// Otherwise just return the "string" (shrug)
return val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment