Go Shorts

1 мин

Здесь я хочу собрать короткие заметки и подсказки о Go

Стартовый набор

Snippets

stringFromEnv

// stringFromEnv retrieves the value of the environment variable named by the `key`.
// It returns the value if variable present and value not empty.
// Otherwise it returns string value `def`.
func stringFromEnv(key string, def string) string {
	if v := os.Getenv(key); v != "" {
		return strings.TrimSpace(v)
	}

	return def
}

intFromEnv

// Retrieves the value of the environment variable named by the `key`
// It returns the value if variable present and valid.
// Otherwise it returns string value `def`.
func intFromEnv(key string, def int) int {
	if v := os.Getenv(key); v != "" {
		i, err := strconv.Atoi(strings.TrimSpace(v))
		if err == nil {
			return i
		}
	}

	return def
}

boolFromEnv

// boolFromEnv retrieves the value of the environment variable named by the `key`.
// It returns the boolean value of the variable if present and valid.
// Otherwise, it returns the default value `def`.
func boolFromEnv(key string, def bool) bool {
	if v := os.Getenv(key); v != "" {
		parsed, err := strconv.ParseBool(strings.TrimSpace(v))
		if err == nil {
			return parsed
		}
	}

	return def
}