value.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2020 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package config
  15. import (
  16. "bytes"
  17. "io/ioutil"
  18. "os"
  19. "strings"
  20. "text/template"
  21. )
  22. var (
  23. glbEnvs map[string]string
  24. )
  25. func init() {
  26. glbEnvs = make(map[string]string)
  27. envs := os.Environ()
  28. for _, env := range envs {
  29. kv := strings.Split(env, "=")
  30. if len(kv) != 2 {
  31. continue
  32. }
  33. glbEnvs[kv[0]] = kv[1]
  34. }
  35. }
  36. type Values struct {
  37. Envs map[string]string // environment vars
  38. }
  39. func GetValues() *Values {
  40. return &Values{
  41. Envs: glbEnvs,
  42. }
  43. }
  44. func RenderContent(in []byte) (out []byte, err error) {
  45. tmpl, errRet := template.New("frp").Parse(string(in))
  46. if errRet != nil {
  47. err = errRet
  48. return
  49. }
  50. buffer := bytes.NewBufferString("")
  51. v := GetValues()
  52. err = tmpl.Execute(buffer, v)
  53. if err != nil {
  54. return
  55. }
  56. out = buffer.Bytes()
  57. return
  58. }
  59. func GetRenderedConfFromFile(path string) (out []byte, err error) {
  60. var b []byte
  61. b, err = ioutil.ReadFile(path)
  62. if err != nil {
  63. return
  64. }
  65. out, err = RenderContent(b)
  66. return
  67. }