env.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. package env
  16. import (
  17. "fmt"
  18. "os"
  19. "strings"
  20. "github.com/astaxie/beego/utils"
  21. )
  22. var env *utils.BeeMap
  23. func init() {
  24. env = utils.NewBeeMap()
  25. for _, e := range os.Environ() {
  26. splits := strings.Split(e, "=")
  27. env.Set(splits[0], os.Getenv(splits[0]))
  28. }
  29. }
  30. // Get returns a value by key.
  31. // If the key does not exist, the default value will be returned.
  32. func Get(key string, defVal string) string {
  33. if val := env.Get(key); val != nil {
  34. return val.(string)
  35. }
  36. return defVal
  37. }
  38. // MustGet returns a value by key.
  39. // If the key does not exist, it will return an error.
  40. func MustGet(key string) (string, error) {
  41. if val := env.Get(key); val != nil {
  42. return val.(string), nil
  43. }
  44. return "", fmt.Errorf("no env variable with %s", key)
  45. }
  46. // Set sets a value in the ENV copy.
  47. // This does not affect the child process environment.
  48. func Set(key string, value string) {
  49. env.Set(key, value)
  50. }
  51. // MustSet sets a value in the ENV copy and the child process environment.
  52. // It returns an error in case the set operation failed.
  53. func MustSet(key string, value string) error {
  54. err := os.Setenv(key, value)
  55. if err != nil {
  56. return err
  57. }
  58. env.Set(key, value)
  59. return nil
  60. }
  61. // GetAll returns all keys/values in the current child process environment.
  62. func GetAll() map[string]string {
  63. items := env.Items()
  64. envs := make(map[string]string, env.Count())
  65. for key, val := range items {
  66. switch key := key.(type) {
  67. case string:
  68. switch val := val.(type) {
  69. case string:
  70. envs[key] = val
  71. }
  72. }
  73. }
  74. return envs
  75. }