env.go 2.2 KB

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