ae25409e56
Motivation: 统一 crypto-strategy 与 trade-signal 两类交易信号的模板字段,使同一套通知模板可复用;字段缺失或为空时不再导致渲染报错或输出空行,通知内容更整洁。 Changes: * 渲染器缺失字段改为按空值处理,新增 line 函数实现空值整行省略 * crypto-strategy 信号补充止盈价、止损价、平均价、收益额等模板字段 * trade-signal 信号保留原始报文中的额外字段以适配统一模板 * 修复结构化日志将 error 作为值直接输出导致的格式问题
61 lines
1.1 KiB
Go
61 lines
1.1 KiB
Go
package engine
|
||
|
||
import (
|
||
"bytes"
|
||
"fmt"
|
||
"strings"
|
||
"text/template"
|
||
)
|
||
|
||
type Renderer struct{}
|
||
|
||
func NewRenderer() *Renderer {
|
||
return &Renderer{}
|
||
}
|
||
|
||
func (r *Renderer) Render(tmplContent string, data map[string]interface{}) (string, error) {
|
||
tmpl, err := template.New("notify").
|
||
Option("missingkey=zero").
|
||
Funcs(template.FuncMap{"line": templateLine}).
|
||
Parse(tmplContent)
|
||
if err != nil {
|
||
return "", fmt.Errorf("parse template: %w", err)
|
||
}
|
||
var buf bytes.Buffer
|
||
if err := tmpl.Execute(&buf, data); err != nil {
|
||
return "", fmt.Errorf("execute template: %w", err)
|
||
}
|
||
return buf.String(), nil
|
||
}
|
||
|
||
// templateLine renders "label:value\n" or empty if value is missing/zero.
|
||
func templateLine(label string, v any) string {
|
||
if isEmptyValue(v) {
|
||
return ""
|
||
}
|
||
return label + ":" + fmt.Sprint(v) + "\n"
|
||
}
|
||
|
||
func isEmptyValue(v any) bool {
|
||
switch t := v.(type) {
|
||
case nil:
|
||
return true
|
||
case string:
|
||
return strings.TrimSpace(t) == ""
|
||
case bool:
|
||
return !t
|
||
case int:
|
||
return t == 0
|
||
case int32:
|
||
return t == 0
|
||
case int64:
|
||
return t == 0
|
||
case float32:
|
||
return t == 0
|
||
case float64:
|
||
return t == 0
|
||
default:
|
||
return false
|
||
}
|
||
}
|