From 3d81f1ad61b36e43754b68195f0730d956616a92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Sun, 2 Jun 2024 00:54:56 +0800 Subject: [PATCH] Fix template extend --- option/template.go | 22 +++++++++++++++++++--- template/manager.go | 8 +++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/option/template.go b/option/template.go index 80bf7db..4904f7f 100644 --- a/option/template.go +++ b/option/template.go @@ -7,9 +7,10 @@ import ( "github.com/sagernet/sing/common/json" ) -type Template struct { - Name string `json:"name,omitempty"` - Extend string `json:"extend,omitempty"` +type _Template struct { + RawMessage json.RawMessage `json:"-"` + Name string `json:"name,omitempty"` + Extend string `json:"extend,omitempty"` // Global @@ -72,6 +73,21 @@ type Template struct { MemoryLimit option.MemoryBytes `json:"memory_limit,omitempty"` } +type Template _Template + +func (t *Template) MarshalJSON() ([]byte, error) { + return json.Marshal((*_Template)(t)) +} + +func (t *Template) UnmarshalJSON(bytes []byte) error { + err := json.Unmarshal(bytes, (*_Template)(t)) + if err != nil { + return err + } + t.RawMessage = bytes + return nil +} + type _RuleSet struct { Type string `json:"type,omitempty"` DefaultOptions option.RuleSet `json:"-"` diff --git a/template/manager.go b/template/manager.go index 9ee5e2a..416f2d5 100644 --- a/template/manager.go +++ b/template/manager.go @@ -7,6 +7,7 @@ import ( "github.com/sagernet/serenity/option" C "github.com/sagernet/sing-box/constant" E "github.com/sagernet/sing/common/exceptions" + "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/json/badjson" "github.com/sagernet/sing/common/logger" ) @@ -40,10 +41,15 @@ func extendTemplate(rawTemplates []option.Template, root, current option.Templat } next = newNext } - newTemplate, err := badjson.Merge(next, current) + newRawTemplate, err := badjson.MergeJSON(next.RawMessage, current.RawMessage) if err != nil { return option.Template{}, E.Cause(err, "initialize template[", current.Name, "]: merge extended template: ", current.Extend) } + newTemplate, err := json.UnmarshalExtended[option.Template](newRawTemplate) + if err != nil { + return option.Template{}, E.Cause(err, "initialize template[", current.Name, "]: unmarshal extended template: ", current.Extend) + } + newTemplate.RawMessage = newRawTemplate return newTemplate, nil }