github.com/astaxie/beego@v1.12.3/config/env/env.go (about) 1 // Copyright 2014 beego Author. All Rights Reserved. 2 // Copyright 2017 Faissal Elamraoui. All Rights Reserved. 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 // Package env is used to parse environment. 17 package env 18 19 import ( 20 "fmt" 21 "os" 22 "strings" 23 24 "github.com/astaxie/beego/utils" 25 ) 26 27 var env *utils.BeeMap 28 29 func init() { 30 env = utils.NewBeeMap() 31 for _, e := range os.Environ() { 32 splits := strings.Split(e, "=") 33 env.Set(splits[0], os.Getenv(splits[0])) 34 } 35 } 36 37 // Get returns a value by key. 38 // If the key does not exist, the default value will be returned. 39 func Get(key string, defVal string) string { 40 if val := env.Get(key); val != nil { 41 return val.(string) 42 } 43 return defVal 44 } 45 46 // MustGet returns a value by key. 47 // If the key does not exist, it will return an error. 48 func MustGet(key string) (string, error) { 49 if val := env.Get(key); val != nil { 50 return val.(string), nil 51 } 52 return "", fmt.Errorf("no env variable with %s", key) 53 } 54 55 // Set sets a value in the ENV copy. 56 // This does not affect the child process environment. 57 func Set(key string, value string) { 58 env.Set(key, value) 59 } 60 61 // MustSet sets a value in the ENV copy and the child process environment. 62 // It returns an error in case the set operation failed. 63 func MustSet(key string, value string) error { 64 err := os.Setenv(key, value) 65 if err != nil { 66 return err 67 } 68 env.Set(key, value) 69 return nil 70 } 71 72 // GetAll returns all keys/values in the current child process environment. 73 func GetAll() map[string]string { 74 items := env.Items() 75 envs := make(map[string]string, env.Count()) 76 77 for key, val := range items { 78 switch key := key.(type) { 79 case string: 80 switch val := val.(type) { 81 case string: 82 envs[key] = val 83 } 84 } 85 } 86 return envs 87 }