pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/env/env.go (about) 1 //go:build !windows 2 // +build !windows 3 4 // Package env provides methods for working with environment variables 5 package env 6 7 // ////////////////////////////////////////////////////////////////////////////////// // 8 // // 9 // Copyright (c) 2022 ESSENTIAL KAOS // 10 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 11 // // 12 // ////////////////////////////////////////////////////////////////////////////////// // 13 14 import ( 15 "os" 16 "strconv" 17 "strings" 18 "syscall" 19 ) 20 21 // ////////////////////////////////////////////////////////////////////////////////// // 22 23 // Env is map with environment values 24 type Env map[string]string 25 26 // ////////////////////////////////////////////////////////////////////////////////// // 27 28 // Get return key-value map with environment values 29 func Get() Env { 30 env := make(Env) 31 32 for _, ev := range os.Environ() { 33 evs := strings.Split(ev, "=") 34 k, v := evs[0], evs[1] 35 36 env[k] = v 37 } 38 39 return env 40 } 41 42 // Which find full path to some app 43 func Which(name string) string { 44 paths := Get().Path() 45 46 for _, path := range paths { 47 if syscall.Access(path+"/"+name, syscall.F_OK) == nil { 48 return path + "/" + name 49 } 50 } 51 52 return "" 53 } 54 55 // ////////////////////////////////////////////////////////////////////////////////// // 56 57 // Path return path as string slice 58 func (e Env) Path() []string { 59 return strings.Split(e["PATH"], ":") 60 } 61 62 // GetS return environment variable value as string 63 func (e Env) GetS(name string) string { 64 return e[name] 65 } 66 67 // GetI return environment variable value as int 68 func (e Env) GetI(name string) int { 69 value, err := strconv.Atoi(e[name]) 70 71 if err != nil { 72 return -1 73 } 74 75 return value 76 } 77 78 // GetF return environment variable value as float 79 func (e Env) GetF(name string) float64 { 80 value, err := strconv.ParseFloat(e[name], 64) 81 82 if err != nil { 83 return -1.0 84 } 85 86 return value 87 }