DEVELOPMENT ENVIRONMENT

~liljamo/erya-go

ref: eabe15b55b1bdbe95d1ae3af5bfd2bae0660e1d2 erya-go/util/env.go -rw-r--r-- 1.3 KiB
eabe15b5Jonni Liljamo chore: update module name a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */
package util

import (
	"log"
	"os"
	"strconv"
)

func LoadEnvStr(key string, def string) string {
	value, found := os.LookupEnv(key)
	if found {
		return value
	}

	if def == "" {
		log.Fatalf("[erya] Environment variable %s is empty, and has no default", key)
	} else {
		log.Printf("[erya] Environment variable %s is empty, using default '%s'", key, def)
	}
	return def
}

func LoadEnvInt32(key string, def int32) int32 {
	value, found := os.LookupEnv(key)
	if found {
		res, err := strconv.ParseInt(value, 10, 32)
		if err != nil {
			log.Fatalf("[erya] Environment variable %s failed to parse to int32 from '%s'", key, value)
		}
		return int32(res)
	}

	log.Printf("[erya] Environment variable %s is empty, using default '%d'", key, def)
	return def
}

func LoadEnvBool(key string, def bool) bool {
	value, found := os.LookupEnv(key)
	if found {
		res, err := strconv.ParseBool(value)
		if err != nil {
			log.Fatalf("[erya] Environment variable %s failed to parse to bool from '%s'", key, value)
		}
		return res
	}

	log.Printf("[erya] Environment variable %s is empty, using default '%t'", key, def)
	return def
}