add template parsing
This commit is contained in:
@@ -2,6 +2,8 @@ package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/AlexxIT/go2rtc/pkg/yaml"
|
||||
@@ -10,6 +12,8 @@ import (
|
||||
var secrets = make(map[string]*Secret)
|
||||
var secretsMu sync.Mutex
|
||||
|
||||
var templateRegex = regexp.MustCompile(`\{\{\s*([^\}]+)\s*\}\}`)
|
||||
|
||||
type Secrets interface {
|
||||
Get(key string) any
|
||||
Set(key string, value any)
|
||||
@@ -53,6 +57,10 @@ func NewSecret(name string, values interface{}) *Secret {
|
||||
return s
|
||||
}
|
||||
|
||||
func GetSecret(name string) *Secret {
|
||||
return secrets[name]
|
||||
}
|
||||
|
||||
func (s *Secret) Get(key string) any {
|
||||
secretsMu.Lock()
|
||||
defer secretsMu.Unlock()
|
||||
@@ -72,6 +80,33 @@ func (s *Secret) Set(key string, value any) {
|
||||
secrets[s.Name] = s
|
||||
}
|
||||
|
||||
func (s *Secret) Parse(template string) string {
|
||||
if !templateRegex.MatchString(template) {
|
||||
return template
|
||||
}
|
||||
|
||||
secretsMu.Lock()
|
||||
defer secretsMu.Unlock()
|
||||
|
||||
if _, exists := secrets[s.Name]; !exists {
|
||||
return template
|
||||
}
|
||||
|
||||
result := templateRegex.ReplaceAllStringFunc(template, func(match string) string {
|
||||
varName := strings.TrimSpace(templateRegex.FindStringSubmatch(match)[1])
|
||||
pathParts := strings.Split(varName, ".")
|
||||
value := getNestedValue(s.Values, pathParts)
|
||||
|
||||
if value != nil {
|
||||
return stringify(value)
|
||||
}
|
||||
|
||||
return ""
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Secret) Marshal(v any) ([]byte, error) {
|
||||
secretsMu.Lock()
|
||||
defer secretsMu.Unlock()
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/AlexxIT/go2rtc/internal/app"
|
||||
"github.com/AlexxIT/go2rtc/pkg/core"
|
||||
)
|
||||
|
||||
@@ -46,6 +47,18 @@ func GetProducer(url string) (core.Producer, error) {
|
||||
}
|
||||
|
||||
if handler, ok := handlers[scheme]; ok {
|
||||
index := strings.IndexByte(url, '#')
|
||||
if index > 0 {
|
||||
_, query := url[:index], ParseQuery(url[index+1:])
|
||||
secretsName := query.Get("secrets")
|
||||
if secretsName != "" {
|
||||
secrets := app.GetSecret(secretsName)
|
||||
if secrets != nil {
|
||||
url = secrets.Parse(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return handler(url)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user