value.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "os"
  18. "strings"
  19. "text/template"
  20. )
  21. var (
  22. glbEnvs map[string]string
  23. )
  24. func init() {
  25. glbEnvs = make(map[string]string)
  26. envs := os.Environ()
  27. for _, env := range envs {
  28. kv := strings.Split(env, "=")
  29. if len(kv) != 2 {
  30. continue
  31. }
  32. glbEnvs[kv[0]] = kv[1]
  33. }
  34. }
  35. type Values struct {
  36. Envs map[string]string // environment vars
  37. }
  38. func GetValues() *Values {
  39. return &Values{
  40. Envs: glbEnvs,
  41. }
  42. }
  43. func RenderContent(in []byte) (out []byte, err error) {
  44. tmpl, errRet := template.New("frp").Parse(string(in))
  45. if errRet != nil {
  46. err = errRet
  47. return
  48. }
  49. buffer := bytes.NewBufferString("")
  50. v := GetValues()
  51. err = tmpl.Execute(buffer, v)
  52. if err != nil {
  53. return
  54. }
  55. out = buffer.Bytes()
  56. return
  57. }
  58. func GetRenderedConfFromFile(path string) (out []byte, err error) {
  59. var b []byte
  60. b, err = os.ReadFile(path)
  61. if err != nil {
  62. return
  63. }
  64. out, err = RenderContent(b)
  65. return
  66. }