Add global variables to be used in templates

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2021-05-25 16:26:03 +02:00
parent 714834e184
commit b6d59045d0
Signed by: luzifer
GPG key ID: 0066F03ED215AD7D
2 changed files with 25 additions and 17 deletions

View file

@ -20,6 +20,7 @@ type configFile struct {
PermitTimeout time.Duration `yaml:"permit_timeout"`
RawLog string `yaml:"raw_log"`
Rules []*rule `yaml:"rules"`
Variables map[string]interface{} `yaml:"variables"`
rawLogWriter io.WriteCloser
}

View file

@ -10,34 +10,41 @@ import (
)
func formatMessage(tplString string, m *irc.Message, r *rule, fields map[string]interface{}) (string, error) {
if fields == nil {
fields = map[string]interface{}{}
compiledFields := map[string]interface{}{}
if config != nil {
configLock.RLock()
for k, v := range config.Variables {
compiledFields[k] = v
}
compiledFields["permitTimeout"] = int64(config.PermitTimeout / time.Second)
configLock.RUnlock()
}
for k, v := range fields {
compiledFields[k] = v
}
if m != nil {
fields["msg"] = m
fields["username"] = m.User
compiledFields["msg"] = m
compiledFields["username"] = m.User
if m.Command == "PRIVMSG" && len(m.Params) > 0 {
fields["channel"] = m.Params[0]
compiledFields["channel"] = m.Params[0]
}
}
if config != nil {
fields["permitTimeout"] = int64(config.PermitTimeout / time.Second)
}
// Parse and execute template
tpl, err := template.
New(tplString).
Funcs(tplFuncs.GetFuncMap(m, r, fields)).
Funcs(tplFuncs.GetFuncMap(m, r, compiledFields)).
Parse(tplString)
if err != nil {
return "", errors.Wrap(err, "parse template")
}
buf := new(bytes.Buffer)
err = tpl.Execute(buf, fields)
err = tpl.Execute(buf, compiledFields)
return buf.String(), errors.Wrap(err, "execute template")
}