From 4c0dcaf106d12d4773feaba3e06eb3b5db2c8e9d Mon Sep 17 00:00:00 2001 From: ClessLi <316600949@qq.com> Date: Tue, 23 Apr 2024 15:05:38 +0800 Subject: [PATCH] feat(resolv): refactored the `Context` `JSON` format serialization structure to simplify serialization/deserialization operations, making the serialization structure more universal and unified. BREAKING CHANGE: Changed the serialization structure of the `Context` `JSON` format, as well as the new functions for the `Directive` and `Comment` context objects. The `Context` `JSON` format serialization structure changes as follows: Before: ```json { "main-config": "C:\\test\\test.conf", "configs": { "C:\\test\\test.conf": [ { "http": { "params": [ { "inline": true, "comments": "test comment" }, { "server": { "params": [ { "directive": "server_name", "params": "testserver" }, { "location": {"value": "~ /test"} }, { "include": { "value": "conf.d\\include*conf", "params": ["conf.d\\include.location1.conf", "conf.d\\include.location2.conf"] } } ] } } ] } } ], "conf.d\\include.location1.conf": [ { "location": {"value": "~ /test1"} } ], "conf.d\\include.location2.conf": [ { "location": {"value": "^~ /test2"} } ] } } ``` After: ```json { "main-config": "C:\\test\\test.conf", "configs": { "C:\\test\\test.conf": { "context-type": "config", "value": "C:\\test\\test.conf", "params": [ { "context-type": "http", "params": [ { "context-type": "inline_comment", "value": "test comment" }, { "context-type": "server", "params": [ { "context-type": "directive", "value": "server_name testserver" }, { "context-type": "location", "value": "~ /test" }, { "context-type": "include", "value": "conf.d\\include*conf", "params": ["conf.d\\include.location1.conf", "conf.d\\include.location2.conf"] } ] } ] } ] }, "conf.d\\include.location1.conf": { "context-type": "config", "value": "conf.d\\include.location1.conf", "params": [ { "context-type": "location", "value": "~ /test1" } ] }, "conf.d\\include.location2.conf": { "context-type": "config", "value": "conf.d\\include.location2.conf", "params": [ { "context-type": "location", "value": "^~ /test2" } ] } } } ``` The code migration example for creating function calls for `Directive` and `Comment` context objects is as follows: Before: ```go import ( "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context/local" ) // new directive context newDirective := local.NewDirective("some_directive", "some params") // new comment context newComment := local.NewComment("some comments", false) newComment := local.NewComment("some inline comments", true) ``` After: ```go import ( "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context/local" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" ) // new directive context newDirective := local.NewContext(context_type.TypeDirective, "some_directive some params") // new comment context newComment := local.NewContext(context_type.TypeComment, "some comments") newInlineComment := local.NewContext(context_type.TypeInlineComment, "some inline comments") ``` --- README.md | 8 +- .../context/local/basic_context.go | 2 +- .../context/local/basic_context_test.go | 146 +-- .../configuration/context/local/comment.go | 44 +- .../context/local/comment_test.go | 56 - .../configuration/context/local/config.go | 7 +- .../context/local/config_test.go | 146 +-- .../configuration/context/local/context.go | 98 +- .../configuration/context/local/directive.go | 39 +- .../context/local/directive_test.go | 44 - .../configuration/context/local/include.go | 25 +- .../context/local/include_test.go | 77 +- .../nginx/configuration/context/local/init.go | 9 - .../context/local/json_unmarshaler.go | 447 +------ .../context/local/json_unmarshaler_test.go | 1062 +++-------------- .../configuration/context/local/loader.go | 2 +- .../context/local/loader_test.go | 10 +- .../context/local/main_context_test.go | 24 +- .../nginx/configuration/nginx_config_test.go | 79 +- test/grpc_client/bifrost/client_test.go | 2 +- 20 files changed, 592 insertions(+), 1735 deletions(-) diff --git a/README.md b/README.md index b3ab0f1..d793c3a 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,7 @@ package main import ( "fmt" + "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context" @@ -286,7 +287,7 @@ func main() { QueryByKeyWords(context.NewKeyWords(context_type.TypeIf).SetRegexpMatchingValue(`^\(\$http_api_name != ''\)$`)).Target(). QueryByKeyWords(context.NewKeyWords(context_type.TypeDirective).SetStringMatchingValue("proxy_pass")).Position() // insert an inline comment after the "proxy_pass" `directive` context - err = ctx.Insert(local.NewComment(fmt.Sprintf("[%s]test comments", time.Now().String()), true), idx+1).Error() + err = ctx.Insert(local.NewContext(context_type.TypeInlineComment, fmt.Sprintf("[%s]test comments", time.Now().String())), idx+1).Error() if err != nil { panic(err) } @@ -308,9 +309,10 @@ func main() { // new main context newMainContext, err := local.NewMain("/usr/local/nginx/conf/nginx.conf") // new directive context - newDirective := local.NewDirective("some_directive", "some params") + newDirective := local.NewContext(context_type.TypeDirective, "some_directive some params") // new comment context - newComment := local.NewComment("some comments", false) + newComment := local.NewContext(context_type.TypeComment, "some comments") + newInlineComment := local.NewContext(context_type.TypeInlineComment, "some inline comments") // new other context newConfig := local.NewContext(context_type.TypeConfig, "conf.d/location.conf") newInclude := local.NewContext(context_type.TypeInclude, "conf.d/*.conf") diff --git a/pkg/resolv/V3/nginx/configuration/context/local/basic_context.go b/pkg/resolv/V3/nginx/configuration/context/local/basic_context.go index 78503a9..b09e8fb 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/basic_context.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/basic_context.go @@ -10,7 +10,7 @@ import ( const INDENT = " " type BasicContext struct { - ContextType context_type.ContextType `json:"-"` + ContextType context_type.ContextType `json:"context-type"` ContextValue string `json:"value,omitempty"` Children []context.Context `json:"params,omitempty"` diff --git a/pkg/resolv/V3/nginx/configuration/context/local/basic_context_test.go b/pkg/resolv/V3/nginx/configuration/context/local/basic_context_test.go index bb6ff03..80afd64 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/basic_context_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/basic_context_test.go @@ -111,16 +111,16 @@ func TestBasicContext_Clone(t *testing.T) { func TestBasicContext_ConfigLines(t *testing.T) { _2levelctx := NewContext(context_type.TypeHttp, "") - _2levelctx.Insert(NewComment("test comment", false), _2levelctx.Len()) + _2levelctx.Insert(NewContext(context_type.TypeComment, "test comment"), _2levelctx.Len()) hasComments2levelctx := _2levelctx.Clone(). - Insert(NewComment("the first inline comment", true), 0). - Insert(NewComment("inline comment after inline comment", true), 1). - Insert(NewComment("inline comment after comment", true), 3). - Insert(NewDirective("test_directive", "aaaa bbbb\n cccc"), 4). - Insert(NewComment("inline comment after other context", true), 5) + Insert(NewContext(context_type.TypeInlineComment, "the first inline comment"), 0). + Insert(NewContext(context_type.TypeInlineComment, "inline comment after inline comment"), 1). + Insert(NewContext(context_type.TypeInlineComment, "inline comment after comment"), 3). + Insert(NewContext(context_type.TypeDirective, "test_directive aaaa bbbb\n cccc"), 4). + Insert(NewContext(context_type.TypeInlineComment, "inline comment after other context"), 5) - _3levelctx := NewContext(context_type.TypeHttp, "").Insert(NewContext(context_type.TypeServer, "").Insert(NewDirective("server_name", "testserver"), 0), 0) + _3levelctx := NewContext(context_type.TypeHttp, "").Insert(NewContext(context_type.TypeServer, "").Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0), 0) includeCtx := NewContext(context_type.TypeInclude, "conf.d/*.conf").(*Include) withIncludeCtx, err := NewMain("C:\\test\\nginx.conf") @@ -141,7 +141,7 @@ func TestBasicContext_ConfigLines(t *testing.T) { includeConfig.self = includeConfig includeConfig.ContextValue = "conf.d\\server.conf" includeConfig.Insert(NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert(NewContext(context_type.TypeLocation, "~ /test"), 1), 0) err = includeCtx.InsertConfig(includeConfig) @@ -191,11 +191,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: _2levelctx.Type(), ContextValue: _2levelctx.Value(), - Children: _2levelctx.(*Http).Children, + Children: _2levelctx.(*BasicContext).Children, father: _2levelctx.Father(), self: _2levelctx, - headStringFunc: _2levelctx.(*Http).headStringFunc, - tailStringFunc: _2levelctx.(*Http).tailStringFunc, + headStringFunc: _2levelctx.(*BasicContext).headStringFunc, + tailStringFunc: _2levelctx.(*BasicContext).tailStringFunc, }, args: args{isDumping: false}, want: []string{ @@ -210,11 +210,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: hasComments2levelctx.Type(), ContextValue: hasComments2levelctx.Value(), - Children: hasComments2levelctx.(*Http).Children, + Children: hasComments2levelctx.(*BasicContext).Children, father: hasComments2levelctx.Father(), self: hasComments2levelctx, - headStringFunc: hasComments2levelctx.(*Http).headStringFunc, - tailStringFunc: hasComments2levelctx.(*Http).tailStringFunc, + headStringFunc: hasComments2levelctx.(*BasicContext).headStringFunc, + tailStringFunc: hasComments2levelctx.(*BasicContext).tailStringFunc, }, args: args{isDumping: false}, want: []string{ @@ -231,11 +231,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: _3levelctx.Type(), ContextValue: _3levelctx.Value(), - Children: _3levelctx.(*Http).Children, + Children: _3levelctx.(*BasicContext).Children, father: _3levelctx.Father(), self: _3levelctx, - headStringFunc: _3levelctx.(*Http).headStringFunc, - tailStringFunc: _3levelctx.(*Http).tailStringFunc, + headStringFunc: _3levelctx.(*BasicContext).headStringFunc, + tailStringFunc: _3levelctx.(*BasicContext).tailStringFunc, }, args: args{isDumping: false}, want: []string{ @@ -251,11 +251,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: withIncludeCtx.Child(0).Type(), ContextValue: withIncludeCtx.Child(0).Value(), - Children: withIncludeCtx.Child(0).(*Http).Children, + Children: withIncludeCtx.Child(0).(*BasicContext).Children, father: withIncludeCtx.Child(0).Father(), self: withIncludeCtx.Child(0), - headStringFunc: withIncludeCtx.Child(0).(*Http).headStringFunc, - tailStringFunc: withIncludeCtx.Child(0).(*Http).tailStringFunc, + headStringFunc: withIncludeCtx.Child(0).(*BasicContext).headStringFunc, + tailStringFunc: withIncludeCtx.Child(0).(*BasicContext).tailStringFunc, }, args: args{isDumping: false}, want: []string{ @@ -323,11 +323,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: _2levelctx.Type(), ContextValue: _2levelctx.Value(), - Children: _2levelctx.(*Http).Children, + Children: _2levelctx.(*BasicContext).Children, father: _2levelctx.Father(), self: _2levelctx, - headStringFunc: _2levelctx.(*Http).headStringFunc, - tailStringFunc: _2levelctx.(*Http).tailStringFunc, + headStringFunc: _2levelctx.(*BasicContext).headStringFunc, + tailStringFunc: _2levelctx.(*BasicContext).tailStringFunc, }, args: args{isDumping: true}, want: []string{ @@ -342,11 +342,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: hasComments2levelctx.Type(), ContextValue: hasComments2levelctx.Value(), - Children: hasComments2levelctx.(*Http).Children, + Children: hasComments2levelctx.(*BasicContext).Children, father: hasComments2levelctx.Father(), self: hasComments2levelctx, - headStringFunc: hasComments2levelctx.(*Http).headStringFunc, - tailStringFunc: hasComments2levelctx.(*Http).tailStringFunc, + headStringFunc: hasComments2levelctx.(*BasicContext).headStringFunc, + tailStringFunc: hasComments2levelctx.(*BasicContext).tailStringFunc, }, args: args{isDumping: true}, want: []string{ @@ -363,11 +363,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: _3levelctx.Type(), ContextValue: _3levelctx.Value(), - Children: _3levelctx.(*Http).Children, + Children: _3levelctx.(*BasicContext).Children, father: _3levelctx.Father(), self: _3levelctx, - headStringFunc: _3levelctx.(*Http).headStringFunc, - tailStringFunc: _3levelctx.(*Http).tailStringFunc, + headStringFunc: _3levelctx.(*BasicContext).headStringFunc, + tailStringFunc: _3levelctx.(*BasicContext).tailStringFunc, }, args: args{isDumping: true}, want: []string{ @@ -383,11 +383,11 @@ func TestBasicContext_ConfigLines(t *testing.T) { fields: fields{ ContextType: withIncludeCtx.Child(0).Type(), ContextValue: withIncludeCtx.Child(0).Value(), - Children: withIncludeCtx.Child(0).(*Http).Children, + Children: withIncludeCtx.Child(0).(*BasicContext).Children, father: withIncludeCtx.Child(0).Father(), self: withIncludeCtx.Child(0), - headStringFunc: withIncludeCtx.Child(0).(*Http).headStringFunc, - tailStringFunc: withIncludeCtx.Child(0).(*Http).tailStringFunc, + headStringFunc: withIncludeCtx.Child(0).(*BasicContext).headStringFunc, + tailStringFunc: withIncludeCtx.Child(0).(*BasicContext).tailStringFunc, }, args: args{isDumping: true}, want: []string{ @@ -585,7 +585,7 @@ func TestBasicContext_HasChild(t *testing.T) { func TestBasicContext_Insert(t *testing.T) { testCtx := NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert(NewContext(context_type.TypeLocation, "~ /test"), 1) type fields struct { ContextType context_type.ContextType @@ -645,7 +645,7 @@ func TestBasicContext_Insert(t *testing.T) { name: "insert invalid error context", fields: fields{Children: make([]context.Context, 0)}, args: args{ - ctx: &Location{BasicContext{ContextType: context_type.TypeErrContext}}, + ctx: &BasicContext{ContextType: context_type.TypeErrContext}, idx: 0, }, want: context.ErrContext(errors.WithCode(code.ErrV3InvalidOperation, "refuse to insert invalid context")), @@ -663,7 +663,7 @@ func TestBasicContext_Insert(t *testing.T) { name: "insert invalid config context", fields: fields{Children: make([]context.Context, 0)}, args: args{ - ctx: &Http{BasicContext{ContextType: context_type.TypeConfig}}, + ctx: &BasicContext{ContextType: context_type.TypeConfig}, idx: 0, }, want: context.ErrContext(errors.WithCode(code.ErrV3InvalidOperation, "refuse to insert invalid context")), @@ -673,10 +673,10 @@ func TestBasicContext_Insert(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{ ctx: NewContext(context_type.TypeLocation, "~ /test2"), @@ -689,10 +689,10 @@ func TestBasicContext_Insert(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{ ctx: NewContext(context_type.TypeLocation, "~ /test3"), @@ -705,10 +705,10 @@ func TestBasicContext_Insert(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{ ctx: &Main{}, @@ -800,11 +800,11 @@ func TestBasicContext_Len(t *testing.T) { func TestBasicContext_Modify(t *testing.T) { testCtx := NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert(NewContext(context_type.TypeLocation, "~ /test"), 1) test2Ctx := testCtx.Clone() hasErrChildCtx := testCtx.Clone() - hasErrChildCtx.(*Server).Children = append(hasErrChildCtx.(*Server).Children, context.NullContext()) + hasErrChildCtx.(*BasicContext).Children = append(hasErrChildCtx.(*BasicContext).Children, context.NullContext()) type fields struct { ContextType context_type.ContextType ContextValue string @@ -828,7 +828,7 @@ func TestBasicContext_Modify(t *testing.T) { name: "modify negative index", fields: fields{Children: make([]context.Context, 0)}, args: args{ - ctx: NewDirective("test", ""), + ctx: NewContext(context_type.TypeDirective, "test"), idx: -1, }, want: context.ErrContext(errors.WithCode(code.ErrV3ContextIndexOutOfRange, "index(%d) out of range", -1)).(*context.ErrorContext).AppendError(context.ErrInsertIntoErrorContext), @@ -869,7 +869,7 @@ func TestBasicContext_Modify(t *testing.T) { name: "modify to an invalid error context", fields: fields{Children: make([]context.Context, 0)}, args: args{ - ctx: &Location{BasicContext{ContextType: context_type.TypeErrContext}}, + ctx: &BasicContext{ContextType: context_type.TypeErrContext}, idx: 0, }, want: context.ErrContext(errors.WithCode(code.ErrV3InvalidOperation, "refuse to modify to invalid context")), @@ -880,10 +880,10 @@ func TestBasicContext_Modify(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{ ctx: NewContext(context_type.TypeLocation, "~ /test2"), @@ -897,10 +897,10 @@ func TestBasicContext_Modify(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{ ctx: NewContext(context_type.TypeLocation, "~ /test3"), @@ -914,10 +914,10 @@ func TestBasicContext_Modify(t *testing.T) { fields: fields{ ContextType: hasErrChildCtx.Type(), ContextValue: hasErrChildCtx.Value(), - Children: hasErrChildCtx.(*Server).Children, + Children: hasErrChildCtx.(*BasicContext).Children, father: hasErrChildCtx.Father(), - headStringFunc: hasErrChildCtx.(*Server).headStringFunc, - tailStringFunc: hasErrChildCtx.(*Server).tailStringFunc, + headStringFunc: hasErrChildCtx.(*BasicContext).headStringFunc, + tailStringFunc: hasErrChildCtx.(*BasicContext).tailStringFunc, }, args: args{ ctx: NewContext(context_type.TypeLocation, "~ /test4"), @@ -933,10 +933,10 @@ func TestBasicContext_Modify(t *testing.T) { fields: fields{ ContextType: test2Ctx.Type(), ContextValue: test2Ctx.Value(), - Children: test2Ctx.(*Server).Children, + Children: test2Ctx.(*BasicContext).Children, father: test2Ctx.Father(), - headStringFunc: test2Ctx.(*Server).headStringFunc, - tailStringFunc: test2Ctx.(*Server).tailStringFunc, + headStringFunc: test2Ctx.(*BasicContext).headStringFunc, + tailStringFunc: test2Ctx.(*BasicContext).tailStringFunc, }, args: args{ ctx: test2Ctx.Child(0), @@ -992,7 +992,7 @@ func TestBasicContext_QueryAllByKeyWords(t *testing.T) { Insert(NewContext(context_type.TypeLocation, "~ /test"), 0). Insert(NewContext(context_type.TypeLocation, "/text"), 1). Insert(NewContext(context_type.TypeLocation, "~ /test2"), 2) - testContext := NewContext(context_type.TypeHttp, "").Insert(testFather, 0).(*Http) + testContext := NewContext(context_type.TypeHttp, "").Insert(testFather, 0).(*BasicContext) type fields struct { ContextType context_type.ContextType ContextValue string @@ -1052,7 +1052,7 @@ func TestBasicContext_QueryByKeyWords(t *testing.T) { Insert(NewContext(context_type.TypeLocation, "~ /test"), 0). Insert(NewContext(context_type.TypeLocation, "/text"), 1). Insert(NewContext(context_type.TypeLocation, "~ /test2"), 2) - testContext := NewContext(context_type.TypeHttp, "").Insert(testFather, 0).(*Http) + testContext := NewContext(context_type.TypeHttp, "").Insert(testFather, 0).(*BasicContext) type fields struct { ContextType context_type.ContextType ContextValue string @@ -1120,10 +1120,10 @@ func TestBasicContext_QueryByKeyWords(t *testing.T) { func TestBasicContext_Remove(t *testing.T) { testCtx := NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert(NewContext(context_type.TypeLocation, "~ /test"), 1) hasErrChildCtx := testCtx.Clone() - hasErrChildCtx.(*Server).Children = append(hasErrChildCtx.(*Server).Children, context.NullContext()) + hasErrChildCtx.(*BasicContext).Children = append(hasErrChildCtx.(*BasicContext).Children, context.NullContext()) type fields struct { ContextType context_type.ContextType ContextValue string @@ -1156,10 +1156,10 @@ func TestBasicContext_Remove(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{idx: 0}, want: testCtx, @@ -1170,10 +1170,10 @@ func TestBasicContext_Remove(t *testing.T) { fields: fields{ ContextType: testCtx.Type(), ContextValue: testCtx.Value(), - Children: testCtx.(*Server).Children, + Children: testCtx.(*BasicContext).Children, father: testCtx.Father(), - headStringFunc: testCtx.(*Server).headStringFunc, - tailStringFunc: testCtx.(*Server).tailStringFunc, + headStringFunc: testCtx.(*BasicContext).headStringFunc, + tailStringFunc: testCtx.(*BasicContext).tailStringFunc, }, args: args{idx: testCtx.Len()}, want: testCtx, @@ -1184,10 +1184,10 @@ func TestBasicContext_Remove(t *testing.T) { fields: fields{ ContextType: hasErrChildCtx.Type(), ContextValue: hasErrChildCtx.Value(), - Children: hasErrChildCtx.(*Server).Children, + Children: hasErrChildCtx.(*BasicContext).Children, father: hasErrChildCtx.Father(), - headStringFunc: hasErrChildCtx.(*Server).headStringFunc, - tailStringFunc: hasErrChildCtx.(*Server).tailStringFunc, + headStringFunc: hasErrChildCtx.(*BasicContext).headStringFunc, + tailStringFunc: hasErrChildCtx.(*BasicContext).tailStringFunc, }, args: args{ idx: hasErrChildCtx.Len() - 1, diff --git a/pkg/resolv/V3/nginx/configuration/context/local/comment.go b/pkg/resolv/V3/nginx/configuration/context/local/comment.go index 4e22c09..831a66d 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/comment.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/comment.go @@ -1,6 +1,7 @@ package local import ( + "encoding/json" "github.com/ClessLi/bifrost/internal/pkg/code" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" @@ -9,12 +10,22 @@ import ( ) type Comment struct { - Comments string `json:"comments"` - Inline bool `json:"inline,omitempty"` + Comments string + Inline bool fatherContext context.Context } +func (c *Comment) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + ContextType context_type.ContextType `json:"context-type"` + Value string `json:"value"` + }{ + ContextType: c.Type(), + Value: c.Value(), + }) +} + func (c *Comment) Insert(ctx context.Context, idx int) context.Context { return context.ErrContext(errors.WithCode(code.ErrV3InvalidOperation, "comment cannot insert context")) } @@ -91,22 +102,33 @@ func (c *Comment) ConfigLines(isDumping bool) ([]string, error) { return []string{"# " + c.Value()}, nil } -func NewComment(comments string, isInline bool) *Comment { - return &Comment{ - Comments: comments, - Inline: isInline, - fatherContext: context.NullContext(), +func registerCommentBuilder() error { + builderMap[context_type.TypeComment] = func(value string) context.Context { + return &Comment{ + Comments: value, + Inline: false, + fatherContext: context.NullContext(), + } } + builderMap[context_type.TypeInlineComment] = func(value string) context.Context { + return &Comment{ + Comments: value, + Inline: true, + fatherContext: context.NullContext(), + } + } + return nil } func registerCommentParseFunc() error { inStackParseFuncMap[context_type.TypeComment] = func(data []byte, idx *int) context.Context { if subMatch := RegCommentHead.FindSubmatch(data[*idx:]); len(subMatch) == 3 { //nolint:nestif matchIndexes := RegCommentHead.FindIndex(data[*idx:]) - cmt := NewComment( - string(subMatch[2]), - !RegLineBreak.Match(subMatch[1]) && *idx != 0, - ) + ct := context_type.TypeComment + if !RegLineBreak.Match(subMatch[1]) && *idx != 0 { + ct = context_type.TypeInlineComment + } + cmt := NewContext(ct, string(subMatch[2])) *idx += matchIndexes[len(matchIndexes)-1] - 1 return cmt diff --git a/pkg/resolv/V3/nginx/configuration/context/local/comment_test.go b/pkg/resolv/V3/nginx/configuration/context/local/comment_test.go index d6f7ff3..4b4a447 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/comment_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/comment_test.go @@ -575,62 +575,6 @@ func TestComment_Value(t *testing.T) { } } -func TestNewComment(t *testing.T) { - type args struct { - comments string - isInline bool - } - tests := []struct { - name string - args args - want *Comment - }{ - { - name: "null value comment", - args: args{ - comments: "", - isInline: false, - }, - want: &Comment{ - Comments: "", - Inline: false, - fatherContext: context.NullContext(), - }, - }, - { - name: "some only space comment", - args: args{ - comments: " \t ", - isInline: true, - }, - want: &Comment{ - Comments: " \t ", - Inline: true, - fatherContext: context.NullContext(), - }, - }, - { - name: "normal comment", - args: args{ - comments: " test comment", - isInline: true, - }, - want: &Comment{ - Comments: " test comment", - Inline: true, - fatherContext: context.NullContext(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := NewComment(tt.args.comments, tt.args.isInline); !reflect.DeepEqual(got, tt.want) { - t.Errorf("NewComment() = %v, want %v", got, tt.want) - } - }) - } -} - func Test_registerCommentParseFunc(t *testing.T) { tests := []struct { name string diff --git a/pkg/resolv/V3/nginx/configuration/context/local/config.go b/pkg/resolv/V3/nginx/configuration/context/local/config.go index aed4d03..d12fcec 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/config.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/config.go @@ -1,7 +1,6 @@ package local import ( - "encoding/json" "github.com/ClessLi/bifrost/internal/pkg/code" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" @@ -13,11 +12,7 @@ import ( type Config struct { BasicContext - context.ConfigPath -} - -func (c *Config) MarshalJSON() ([]byte, error) { - return json.Marshal(c.BasicContext.Children) + context.ConfigPath `json:"-"` } func (c *Config) isInGraph() bool { diff --git a/pkg/resolv/V3/nginx/configuration/context/local/config_test.go b/pkg/resolv/V3/nginx/configuration/context/local/config_test.go index 65ee3dd..740845b 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/config_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/config_test.go @@ -15,10 +15,10 @@ func TestConfig_Clone(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -96,10 +96,10 @@ func TestConfig_ConfigLines(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -225,47 +225,47 @@ func TestConfig_checkIncludedConfigs(t *testing.T) { } } -func TestConfig_MarshalJSON(t *testing.T) { - type fields struct { - BasicContext BasicContext - ConfigPath context.ConfigPath - } - tests := []struct { - name string - fields fields - want []byte - wantErr bool - }{ - { - name: "null children", - fields: fields{BasicContext: BasicContext{Children: make([]context.Context, 0)}}, - want: []byte("[]"), - wantErr: false, - }, - { - name: "normal test", - fields: fields{BasicContext: BasicContext{Children: []context.Context{NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver.com"), 0)}}}, - want: []byte(`[{"server":{"params":[{"directive":"server_name","params":"testserver.com"}]}}]`), - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - c := &Config{ - BasicContext: tt.fields.BasicContext, - ConfigPath: tt.fields.ConfigPath, - } - got, err := c.MarshalJSON() - if (err != nil) != tt.wantErr { - t.Errorf("MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("MarshalJSON() got = %s, want %s", got, tt.want) - } - }) - } -} +//func TestConfig_MarshalJSON(t *testing.T) { +// type fields struct { +// BasicContext BasicContext +// ConfigPath context.ConfigPath +// } +// tests := []struct { +// name string +// fields fields +// want []byte +// wantErr bool +// }{ +// { +// name: "null children", +// fields: fields{BasicContext: BasicContext{Children: make([]context.Context, 0)}}, +// want: []byte("[]"), +// wantErr: false, +// }, +// { +// name: "normal test", +// fields: fields{BasicContext: BasicContext{Children: []context.Context{NewContext(context_type.TypeServer, ""). +// Insert(NewDirective("server_name", "testserver.com"), 0)}}}, +// want: []byte(`[{"server":{"params":[{"directive":"server_name","params":"testserver.com"}]}}]`), +// }, +// } +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// c := &Config{ +// BasicContext: tt.fields.BasicContext, +// ConfigPath: tt.fields.ConfigPath, +// } +// got, err := c.MarshalJSON() +// if (err != nil) != tt.wantErr { +// t.Errorf("MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) +// return +// } +// if !reflect.DeepEqual(got, tt.want) { +// t.Errorf("MarshalJSON() got = %s, want %s", got, tt.want) +// } +// }) +// } +//} func TestConfig_SetFather(t *testing.T) { testMain, err := NewMain("C:\\test\\test.conf") @@ -322,10 +322,10 @@ func TestConfig_SetValue(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -399,10 +399,10 @@ func TestConfig_includeConfig(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -660,10 +660,10 @@ func TestConfig_isInGraph(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -753,10 +753,10 @@ func TestConfig_modifyPathInGraph(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -847,10 +847,10 @@ func TestConfig_removeIncludedConfig(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -986,10 +986,10 @@ func Test_configGraph_AddConfig(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1055,10 +1055,10 @@ func Test_configGraph_AddEdge(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1211,10 +1211,10 @@ func Test_configGraph_GetConfig(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1306,10 +1306,10 @@ func Test_configGraph_RemoveEdge(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1381,10 +1381,10 @@ func Test_configGraph_RenewConfigPath(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1480,10 +1480,10 @@ func Test_configGraph_Topology(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1544,10 +1544,10 @@ func Test_configGraph_removeConfig(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1628,10 +1628,10 @@ func Test_configGraph_setFatherFor(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -1705,10 +1705,10 @@ func Test_configHash(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, diff --git a/pkg/resolv/V3/nginx/configuration/context/local/context.go b/pkg/resolv/V3/nginx/configuration/context/local/context.go index 7defea8..ffd51b3 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/context.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/context.go @@ -23,8 +23,8 @@ func OptsApplyTo(opts context.BuildOptions) (BuildBasicContextConfig, error) { return buildConfig, nil } -func (b BuildBasicContextConfig) BasicContext() BasicContext { - return BasicContext{ +func (b BuildBasicContextConfig) BasicContext() *BasicContext { + return &BasicContext{ ContextType: b.ContextType, Children: make([]context.Context, 0), father: context.NullContext(), @@ -33,7 +33,7 @@ func (b BuildBasicContextConfig) BasicContext() BasicContext { } } -type ContextBuilderRegistrar func(func() BasicContext) func(value string) context.Context +type ContextBuilderRegistrar func(func() *BasicContext) func(value string) context.Context func hasValueBraceHeadString(ctxType context_type.ContextType, value string) string { contextTitle := ctxType.String() @@ -119,10 +119,6 @@ func buildHeadAndTailStringFuncs(options context.BuildOptions) (func(context_typ return head, tail } -type Events struct { - BasicContext `json:"events"` -} - func registerEventsBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -130,9 +126,9 @@ func registerEventsBuilder() error { ParseType: context.ParseContext, HasValue: false, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(_ string) context.Context { - ctx := &Events{f()} + ctx := f() ctx.self = ctx return ctx } @@ -151,10 +147,6 @@ func registerEventsParseFunc() error { ) } -type Geo struct { - BasicContext `json:"geo"` -} - func registerGeoBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -162,9 +154,9 @@ func registerGeoBuilder() error { ParseType: context.ParseContext, HasValue: true, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(value string) context.Context { - ctx := &Geo{f()} + ctx := f() ctx.ContextValue = value ctx.self = ctx return ctx @@ -184,10 +176,6 @@ func registerGeoParseFunc() error { ) } -type Http struct { - BasicContext `json:"http"` -} - func registerHttpBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -195,9 +183,9 @@ func registerHttpBuilder() error { ParseType: context.ParseContext, HasValue: false, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(_ string) context.Context { - ctx := &Http{f()} + ctx := f() ctx.self = ctx return ctx } @@ -216,10 +204,6 @@ func registerHttpParseFunc() error { ) } -type If struct { - BasicContext `json:"if"` -} - func registerIfBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -227,9 +211,9 @@ func registerIfBuilder() error { ParseType: context.ParseContext, HasValue: true, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(value string) context.Context { - ctx := &If{f()} + ctx := f() ctx.ContextValue = value ctx.self = ctx return ctx @@ -249,10 +233,6 @@ func registerIfParseFunc() error { ) } -type LimitExcept struct { - BasicContext `json:"limit_except"` -} - func registerLimitExceptBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -260,9 +240,9 @@ func registerLimitExceptBuilder() error { ParseType: context.ParseContext, HasValue: true, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(value string) context.Context { - ctx := &LimitExcept{f()} + ctx := f() ctx.ContextValue = value ctx.self = ctx return ctx @@ -282,10 +262,6 @@ func registerLimitExceptParseFunc() error { ) } -type Location struct { - BasicContext `json:"location"` -} - func registerLocationBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -293,9 +269,9 @@ func registerLocationBuilder() error { ParseType: context.ParseContext, HasValue: true, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(value string) context.Context { - ctx := &Location{f()} + ctx := f() ctx.ContextValue = value ctx.self = ctx return ctx @@ -315,10 +291,6 @@ func registerLocationParseFunc() error { ) } -type Map struct { - BasicContext `json:"map"` -} - func registerMapBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -326,9 +298,9 @@ func registerMapBuilder() error { ParseType: context.ParseContext, HasValue: true, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(value string) context.Context { - ctx := &Map{f()} + ctx := f() ctx.ContextValue = value ctx.self = ctx return ctx @@ -348,10 +320,6 @@ func registerMapParseFunc() error { ) } -type Server struct { - BasicContext `json:"server"` -} - func registerServerBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -359,9 +327,9 @@ func registerServerBuilder() error { ParseType: context.ParseContext, HasValue: false, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(_ string) context.Context { - ctx := &Server{f()} + ctx := f() ctx.self = ctx return ctx } @@ -380,10 +348,6 @@ func registerServerParseFunc() error { ) } -type Stream struct { - BasicContext `json:"stream"` -} - func registerStreamBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -391,9 +355,9 @@ func registerStreamBuilder() error { ParseType: context.ParseContext, HasValue: false, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(_ string) context.Context { - ctx := &Stream{f()} + ctx := f() ctx.self = ctx return ctx } @@ -412,10 +376,6 @@ func registerStreamParseFunc() error { ) } -type Types struct { - BasicContext `json:"types"` -} - func registerTypesBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -423,9 +383,9 @@ func registerTypesBuilder() error { ParseType: context.ParseContext, HasValue: false, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(_ string) context.Context { - ctx := &Types{f()} + ctx := f() ctx.self = ctx return ctx } @@ -444,10 +404,6 @@ func registerTypesParseFunc() error { ) } -type Upstream struct { - BasicContext `json:"upstream"` -} - func registerUpstreamBuilder() error { return RegisterBuilder( context.BuildOptions{ @@ -455,9 +411,9 @@ func registerUpstreamBuilder() error { ParseType: context.ParseContext, HasValue: true, }, - func(f func() BasicContext) func(value string) context.Context { + func(f func() *BasicContext) func(value string) context.Context { return func(value string) context.Context { - ctx := &Upstream{f()} + ctx := f() ctx.ContextValue = value ctx.self = ctx return ctx @@ -488,8 +444,10 @@ func NewContext(contextType context_type.ContextType, value string) context.Cont func registerContextBuilders() error { errs := make([]error, 0) errs = append(errs, + registerCommentBuilder(), registerConfigBuilder(), - registerIncludeBuild(), + registerDirectiveBuilder(), + registerIncludeBuilder(), registerEventsBuilder(), registerGeoBuilder(), registerHttpBuilder(), diff --git a/pkg/resolv/V3/nginx/configuration/context/local/directive.go b/pkg/resolv/V3/nginx/configuration/context/local/directive.go index 5f60af8..cf07af8 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/directive.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/directive.go @@ -1,6 +1,7 @@ package local import ( + "encoding/json" "github.com/ClessLi/bifrost/internal/pkg/code" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" @@ -9,12 +10,22 @@ import ( ) type Directive struct { - Name string `json:"directive"` - Params string `json:"params,omitempty"` + Name string + Params string fatherContext context.Context } +func (d *Directive) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + ContextType context_type.ContextType `json:"context-type"` + Value string `json:"value"` + }{ + ContextType: d.Type(), + Value: d.Value(), + }) +} + func (d *Directive) Insert(ctx context.Context, idx int) context.Context { return context.ErrContext(errors.WithCode(code.ErrV3InvalidOperation, "directive cannot insert context")) } @@ -98,12 +109,22 @@ func (d *Directive) ConfigLines(isDumping bool) ([]string, error) { return []string{d.Value() + ";"}, nil } -func NewDirective(name, params string) *Directive { - return &Directive{ - Name: strings.TrimSpace(name), - Params: strings.TrimSpace(params), - fatherContext: context.NullContext(), +func registerDirectiveBuilder() error { + builderMap[context_type.TypeDirective] = func(value string) context.Context { + kv := strings.SplitN(strings.TrimSpace(value), " ", 2) + if len(strings.TrimSpace(kv[0])) == 0 { + return context.ErrContext(errors.New("null value")) + } + d := &Directive{ + Name: strings.TrimSpace(kv[0]), + fatherContext: context.NullContext(), + } + if len(kv) == 2 { + d.Params = strings.TrimSpace(kv[1]) + } + return d } + return nil } func registerDirectiveParseFunc() error { @@ -112,7 +133,7 @@ func registerDirectiveParseFunc() error { subMatch := RegDirectiveWithoutValue.FindSubmatch(data[*idx:]) *idx += matchIndexes[len(matchIndexes)-1] key := string(subMatch[1]) - return NewDirective(key, "") + return NewContext(context_type.TypeDirective, key) } if matchIndexes := RegDirectiveWithValue.FindIndex(data[*idx:]); matchIndexes != nil { //nolint:nestif @@ -123,7 +144,7 @@ func registerDirectiveParseFunc() error { if name == string(context_type.TypeInclude) { return context.NullContext() } - return NewDirective(name, value) + return NewContext(context_type.TypeDirective, name+" "+value) } return context.NullContext() } diff --git a/pkg/resolv/V3/nginx/configuration/context/local/directive_test.go b/pkg/resolv/V3/nginx/configuration/context/local/directive_test.go index 261bf18..dab0f95 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/directive_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/directive_test.go @@ -634,47 +634,3 @@ func TestDirective_Value(t *testing.T) { }) } } - -func TestNewDirective(t *testing.T) { - type args struct { - name string - params string - } - tests := []struct { - name string - args args - want *Directive - }{ - { - name: "new directive without params", - args: args{ - name: " test_directive ", - params: "", - }, - want: &Directive{ - Name: "test_directive", - Params: "", - fatherContext: context.NullContext(), - }, - }, - { - name: "new directive with params", - args: args{ - name: " test_directive ", - params: " param1 param2\n param3 ", - }, - want: &Directive{ - Name: "test_directive", - Params: "param1 param2\n param3", - fatherContext: context.NullContext(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := NewDirective(tt.args.name, tt.args.params); !reflect.DeepEqual(got, tt.want) { - t.Errorf("NewDirective() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/pkg/resolv/V3/nginx/configuration/context/local/include.go b/pkg/resolv/V3/nginx/configuration/context/local/include.go index fa3e97d..20e4fed 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/include.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/include.go @@ -10,28 +10,25 @@ import ( ) type Include struct { - ContextValue string `json:"value,omitempty"` - Configs map[string]*Config `json:"param,omitempty"` + ContextValue string + Configs map[string]*Config fatherContext context.Context } func (i *Include) MarshalJSON() ([]byte, error) { marshalCtx := struct { - Include struct { - Value string `json:"value,omitempty"` - Params []string `json:"params,omitempty"` - } `json:"include,omitempty"` - }{Include: struct { - Value string `json:"value,omitempty"` - Params []string `json:"params,omitempty"` + ContextType context_type.ContextType `json:"context-type"` + Value string `json:"value,omitempty"` + Params []string `json:"params,omitempty"` }(struct { - Value string - Params []string - }{Value: i.Value(), Params: make([]string, 0)})} + ContextType context_type.ContextType + Value string + Params []string + }{ContextType: context_type.TypeInclude, Value: i.ContextValue, Params: make([]string, 0)}) for _, config := range i.Configs { - marshalCtx.Include.Params = append(marshalCtx.Include.Params, config.Value()) + marshalCtx.Params = append(marshalCtx.Params, config.Value()) } return json.Marshal(marshalCtx) } @@ -243,7 +240,7 @@ func (i *Include) matchConfigPath(path string) error { return nil } -func registerIncludeBuild() error { +func registerIncludeBuilder() error { builderMap[context_type.TypeInclude] = func(value string) context.Context { return &Include{ ContextValue: value, diff --git a/pkg/resolv/V3/nginx/configuration/context/local/include_test.go b/pkg/resolv/V3/nginx/configuration/context/local/include_test.go index 9c1e7c7..10dba43 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/include_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/include_test.go @@ -182,13 +182,13 @@ func TestInclude_ConfigLines(t *testing.T) { Insert( NewContext(context_type.TypeLocation, "~ /test"). Insert( - NewDirective("proxy_pass", "https://www.baidu.com"), + NewContext(context_type.TypeDirective, "proxy_pass https://www.baidu.com"), 0, ), 0, ). Insert( - NewDirective("server_name", "testserver.com"), + NewContext(context_type.TypeDirective, "server_name testserver.com"), 0, ), 0, @@ -659,10 +659,10 @@ func TestInclude_ModifyConfig(t *testing.T) { } modifiedRelConfig := relConfig.Clone().(*Config) modifiedRelConfig.ConfigPath, _ = newConfigPath(testMain, modifiedRelConfig.Value()) - modifiedRelConfig.Insert(NewDirective("keepalive_timeout", "300s"), 0) + modifiedRelConfig.Insert(NewContext(context_type.TypeDirective, "keepalive_timeout 300s"), 0) modifiedAbsConfig := absConfig.Clone().(*Config) modifiedAbsConfig.ConfigPath, _ = newConfigPath(testMain, modifiedAbsConfig.Value()) - modifiedAbsConfig.Insert(NewDirective("proxy_http_version", "1.1"), 0) + modifiedAbsConfig.Insert(NewContext(context_type.TypeDirective, "proxy_http_version 1.1"), 0) unboundedConfig := NewContext(context_type.TypeConfig, "unbound.conf") unboundedInclude := NewContext(context_type.TypeInclude, "unbound.*.conf").(*Include) @@ -1264,8 +1264,8 @@ func Test_registerIncludeBuild(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := registerIncludeBuild(); (err != nil) != tt.wantErr { - t.Errorf("registerIncludeBuild() error = %v, wantErr %v", err, tt.wantErr) + if err := registerIncludeBuilder(); (err != nil) != tt.wantErr { + t.Errorf("registerIncludeBuilder() error = %v, wantErr %v", err, tt.wantErr) } }) } @@ -1286,3 +1286,68 @@ func Test_registerIncludeParseFunc(t *testing.T) { }) } } + +func TestInclude_MarshalJSON(t *testing.T) { + testMain, err := NewMain("C:\\test\\nginx.conf") + if err != nil { + t.Fatal(err) + } + testInclude := NewContext(context_type.TypeInclude, "*.conf").(*Include) + testMain.Insert( + NewContext(context_type.TypeHttp, ""). + Insert( + testInclude, + 0, + ), + 0, + ) + relConfig := NewContext(context_type.TypeConfig, "relative.conf").(*Config) + relConfig.ConfigPath, _ = newConfigPath(testMain, relConfig.ContextValue) + absConfig := NewContext(context_type.TypeConfig, "C:\\test\\absolut.conf").(*Config) + absConfig.ConfigPath, _ = newConfigPath(testMain, absConfig.ContextValue) + notMatchConfig := NewContext(context_type.TypeConfig, "test\\test.conf").(*Config) + notMatchConfig.ConfigPath, _ = newConfigPath(testMain, notMatchConfig.ContextValue) + err = testInclude.InsertConfig(relConfig, absConfig) + if err != nil { + t.Fatal(err) + } + type fields struct { + ContextValue string + Configs map[string]*Config + fatherContext context.Context + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + { + name: "normal test", + fields: fields{ + ContextValue: testInclude.ContextValue, + Configs: testInclude.Configs, + fatherContext: testInclude.fatherContext, + }, + want: []byte(`{"context-type":"include","value":"*.conf","params":["relative.conf","C:\\test\\absolut.conf"]}`), + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + i := &Include{ + ContextValue: tt.fields.ContextValue, + Configs: tt.fields.Configs, + fatherContext: tt.fields.fatherContext, + } + got, err := i.MarshalJSON() + if (err != nil) != tt.wantErr { + t.Errorf("MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MarshalJSON() got = %s, want %s", got, tt.want) + } + }) + } +} diff --git a/pkg/resolv/V3/nginx/configuration/context/local/init.go b/pkg/resolv/V3/nginx/configuration/context/local/init.go index 6690053..2cacf7d 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/init.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/init.go @@ -9,13 +9,4 @@ func init() { if err != nil { panic(err) } - - err = registerJsonRegMatchers() - if err != nil { - panic(err) - } - err = registerJsonUnmarshalerBuilders() - if err != nil { - panic(err) - } } diff --git a/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler.go b/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler.go index 197358c..61c3c83 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler.go @@ -5,313 +5,41 @@ import ( "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" "github.com/marmotedu/errors" - "regexp" "strings" ) -type JsonUnmarshalContext interface { - Type() context_type.ContextType - GetValue() string - GetChildren() []*json.RawMessage -} - type jsonUnmarshalContext struct { - Value string `json:"value,omitempty"` - Children []*json.RawMessage `json:"params,omitempty"` - contextType context_type.ContextType -} - -func (u jsonUnmarshalContext) Type() context_type.ContextType { - return u.contextType -} - -func (u jsonUnmarshalContext) GetValue() string { - return u.Value -} - -func (u jsonUnmarshalContext) GetChildren() []*json.RawMessage { - return u.Children + ContextType context_type.ContextType `json:"context-type"` + Value string `json:"value,omitempty"` + Children []*json.RawMessage `json:"params,omitempty"` } type jsonUnmarshalMain struct { - MainConfig string `json:"main-config,omitempty"` - Configs map[string][]*json.RawMessage `json:"configs,omitempty"` -} - -type jsonUnmarshalComment struct { - Comments string `json:"comments,omitempty"` - Inline bool `json:"inline,omitempty"` -} - -func (c jsonUnmarshalComment) Type() context_type.ContextType { - if c.Inline { - return context_type.TypeInlineComment - } - return context_type.TypeComment -} - -func (c jsonUnmarshalComment) GetValue() string { - return c.Comments -} - -func (c jsonUnmarshalComment) GetChildren() []*json.RawMessage { - return []*json.RawMessage{} -} - -func registerCommentJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeComment, JsonUnmarshalRegCommentHead) -} - -func registerCommentJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeComment, func() JsonUnmarshalContext { - return new(jsonUnmarshalComment) - }) -} - -type jsonUnmarshalConfig struct { - jsonUnmarshalContext `json:"config"` -} - -type jsonUnmarshalDirective struct { - Name string `json:"directive,omitempty"` - Params string `json:"params,omitempty"` -} - -func (d jsonUnmarshalDirective) Type() context_type.ContextType { - return context_type.TypeDirective -} - -func (d jsonUnmarshalDirective) GetValue() string { - v := strings.TrimSpace(d.Name) - if params := strings.TrimSpace(d.Params); len(params) > 0 { - v += " " + params - } - return v -} - -func (d jsonUnmarshalDirective) GetChildren() []*json.RawMessage { - return []*json.RawMessage{} -} - -func registerDirectiveJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeDirective, func() JsonUnmarshalContext { - return new(jsonUnmarshalDirective) - }) -} - -type jsonUnmarshalEvents struct { - jsonUnmarshalContext `json:"events"` -} - -func registerEventsJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeEvents, JsonUnmarshalRegEventsHead) -} - -func registerEventsJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeEvents, func() JsonUnmarshalContext { - u := new(jsonUnmarshalEvents) - u.contextType = context_type.TypeEvents - return u - }) -} - -type jsonUnmarshalGeo struct { - jsonUnmarshalContext `json:"geo"` -} - -func registerGEOJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeGeo, JsonUnmarshalRegGeoHead) -} - -func registerGEOJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeGeo, func() JsonUnmarshalContext { - u := new(jsonUnmarshalGeo) - u.contextType = context_type.TypeGeo - return u - }) -} - -type jsonUnmarshalHttp struct { - jsonUnmarshalContext `json:"http"` -} - -func registerHTTPJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeHttp, JsonUnmarshalRegHttpHead) -} - -func registerHTTPJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeHttp, func() JsonUnmarshalContext { - u := new(jsonUnmarshalHttp) - u.contextType = context_type.TypeHttp - return u - }) -} - -type jsonUnmarshalIf struct { - jsonUnmarshalContext `json:"if"` -} - -func registerIFJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeIf, JsonUnmarshalRegIfHead) -} - -func registerIFJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeIf, func() JsonUnmarshalContext { - u := new(jsonUnmarshalIf) - u.contextType = context_type.TypeIf - return u - }) -} - -type jsonUnmarshalInclude struct { - jsonUnmarshalContext `json:"include"` -} - -func registerIncludeJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeInclude, JsonUnmarshalRegIncludeHead) -} - -func registerIncludeJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeInclude, func() JsonUnmarshalContext { - u := new(jsonUnmarshalInclude) - u.contextType = context_type.TypeInclude - return u - }) -} - -type jsonUnmarshalLimitExcept struct { - jsonUnmarshalContext `json:"limit-except"` -} - -func registerLimitExceptJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeLimitExcept, JsonUnmarshalRegLimitExceptHead) -} - -func registerLimitExceptJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeLimitExcept, func() JsonUnmarshalContext { - u := new(jsonUnmarshalLimitExcept) - u.contextType = context_type.TypeLimitExcept - return u - }) -} - -type jsonUnmarshalLocation struct { - jsonUnmarshalContext `json:"location"` -} - -func registerLocationJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeLocation, JsonUnmarshalRegLocationHead) -} - -func registerLocationJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeLocation, func() JsonUnmarshalContext { - u := new(jsonUnmarshalLocation) - u.contextType = context_type.TypeLocation - return u - }) -} - -type jsonUnmarshalMap struct { - jsonUnmarshalContext `json:"map"` -} - -func registerMapJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeMap, JsonUnmarshalRegMapHead) -} - -func registerMapJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeMap, func() JsonUnmarshalContext { - u := new(jsonUnmarshalMap) - u.contextType = context_type.TypeMap - return u - }) -} - -type jsonUnmarshalServer struct { - jsonUnmarshalContext `json:"server"` -} - -func registerServerJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeServer, JsonUnmarshalRegServerHead) -} - -func registerServerJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeServer, func() JsonUnmarshalContext { - u := new(jsonUnmarshalServer) - u.contextType = context_type.TypeServer - return u - }) -} - -type jsonUnmarshalStream struct { - jsonUnmarshalContext `json:"stream"` -} - -func registerStreamJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeStream, JsonUnmarshalRegStreamHead) -} - -func registerStreamJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeStream, func() JsonUnmarshalContext { - u := new(jsonUnmarshalStream) - u.contextType = context_type.TypeStream - return u - }) -} - -type jsonUnmarshalTypes struct { - jsonUnmarshalContext `json:"types"` -} - -func registerTypesJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeTypes, JsonUnmarshalRegTypesHead) -} - -func registerTypesJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeTypes, func() JsonUnmarshalContext { - u := new(jsonUnmarshalTypes) - u.contextType = context_type.TypeTypes - return u - }) -} - -type jsonUnmarshalUpstream struct { - jsonUnmarshalContext `json:"upstream"` -} - -func registerUpstreamJsonRegMatcher() error { - return RegisterJsonRegMatcher(context_type.TypeUpstream, JsonUnmarshalRegUpstreamHead) -} - -func registerUpstreamJsonUnmarshalerBuilder() error { - return RegisterJsonUnmarshalerBuilder(context_type.TypeUpstream, func() JsonUnmarshalContext { - u := new(jsonUnmarshalUpstream) - u.contextType = context_type.TypeUpstream - return u - }) + MainConfig string `json:"main-config,omitempty"` + Configs map[string]*json.RawMessage `json:"configs,omitempty"` } type mainUnmarshaler struct { - unmarshalContext *jsonUnmarshalMain - completedMain MainContext + completedMain MainContext } func (m *mainUnmarshaler) UnmarshalJSON(bytes []byte) error { - err := json.Unmarshal(bytes, m.unmarshalContext) + var unmarshalMain jsonUnmarshalMain + err := json.Unmarshal(bytes, &unmarshalMain) if err != nil { return err } - main, err := NewMain(m.unmarshalContext.MainConfig) + main, err := NewMain(unmarshalMain.MainConfig) if err != nil { return err } m.completedMain = main - toBeUnmarshalledConfigs := make(map[string]*jsonUnmarshalConfig) - for value, rawMessages := range m.unmarshalContext.Configs { - var configHashString string - if value != m.unmarshalContext.MainConfig { + // add configs into graph + for value := range unmarshalMain.Configs { + //var configHashString string + if value != unmarshalMain.MainConfig { config, ok := NewContext(context_type.TypeConfig, value).(*Config) if !ok { return errors.Errorf("failed to build config '%v'", value) @@ -324,33 +52,20 @@ func (m *mainUnmarshaler) UnmarshalJSON(bytes []byte) error { if err != nil { return err } - configHashString = configHash(config) - } else { - configHashString = configHash(m.completedMain.MainConfig()) } - toBeUnmarshalledConfigs[configHashString] = &jsonUnmarshalConfig{jsonUnmarshalContext{ - Value: value, - Children: rawMessages, - contextType: context_type.TypeConfig, - }} + } // unmarshal configs - for configHashString, unmarshalConfig := range toBeUnmarshalledConfigs { - cache, err := m.completedMain.GetConfig(configHashString) - if err != nil { - return err - } - unmarshaler := &jsonUnmarshaler{ - unmarshalContext: unmarshalConfig, + for _, configRaw := range unmarshalMain.Configs { + configMarshaler := jsonUnmarshaler{ configGraph: m.completedMain.graph(), - completedContext: cache, + completedContext: context.NullContext(), + fatherContext: m.completedMain, } - for _, childRaw := range unmarshaler.unmarshalContext.GetChildren() { - err = unmarshaler.nextUnmarshaler(childRaw).UnmarshalJSON(*childRaw) - if err != nil { - return err - } + err = configMarshaler.UnmarshalJSON(*configRaw) + if err != nil { + return err } } @@ -358,33 +73,30 @@ func (m *mainUnmarshaler) UnmarshalJSON(bytes []byte) error { } type jsonUnmarshaler struct { - unmarshalContext JsonUnmarshalContext configGraph ConfigGraph completedContext context.Context fatherContext context.Context } func (u *jsonUnmarshaler) UnmarshalJSON(bytes []byte) error { + var unmarshalCtx jsonUnmarshalContext // unmarshal context, it's self - err := json.Unmarshal(bytes, u.unmarshalContext) + err := json.Unmarshal(bytes, &unmarshalCtx) if err != nil { return err } - switch u.unmarshalContext.Type() { + switch unmarshalCtx.ContextType { case context_type.TypeConfig: - return errors.New("invalid JSON data: the unmarshal operation for config should be completed in the unmarshal operation of the main unmarshaler") + err = u.unmarshalConfig(&unmarshalCtx) + if err != nil { + return err + } case context_type.TypeInclude: // insert the include context to be unmarshalled into its father, and unmarshal itself - return u.unmarshalInclude() - case context_type.TypeComment: - return u.fatherContext.Insert(NewComment(u.unmarshalContext.GetValue(), false), u.fatherContext.Len()).Error() - case context_type.TypeInlineComment: - return u.fatherContext.Insert(NewComment(u.unmarshalContext.GetValue(), true), u.fatherContext.Len()).Error() - case context_type.TypeDirective: - return u.fatherContext.Insert(NewDirective(u.unmarshalContext.(*jsonUnmarshalDirective).Name, u.unmarshalContext.(*jsonUnmarshalDirective).Params), u.fatherContext.Len()).Error() + return u.unmarshalInclude(&unmarshalCtx) default: - u.completedContext = NewContext(u.unmarshalContext.Type(), u.unmarshalContext.GetValue()) + u.completedContext = NewContext(unmarshalCtx.ContextType, unmarshalCtx.Value) if err = u.completedContext.Error(); err != nil { return err } @@ -396,8 +108,8 @@ func (u *jsonUnmarshaler) UnmarshalJSON(bytes []byte) error { } // unmarshal context's children - for _, childRaw := range u.unmarshalContext.GetChildren() { - err = u.nextUnmarshaler(childRaw).UnmarshalJSON(*childRaw) + for _, childRaw := range unmarshalCtx.Children { + err = u.nextUnmarshaler().UnmarshalJSON(*childRaw) if err != nil { return err } @@ -405,24 +117,29 @@ func (u *jsonUnmarshaler) UnmarshalJSON(bytes []byte) error { return nil } -func (u *jsonUnmarshaler) nextUnmarshaler(message *json.RawMessage) *jsonUnmarshaler { - matchedType := context_type.TypeDirective - for contextType, matcher := range jsonUnmarshalRegMatcherMap { - if matcher(*message) { - matchedType = contextType - break - } +func (u *jsonUnmarshaler) nextUnmarshaler() *jsonUnmarshaler { + return &jsonUnmarshaler{ + configGraph: u.configGraph, + completedContext: context.NullContext(), + fatherContext: u.completedContext, } - - return jsonUnmarshalerBuilderMap[matchedType](u.configGraph, u.completedContext) } -func (u *jsonUnmarshaler) unmarshalInclude() error { - unmarshalInclude, ok := u.unmarshalContext.(*jsonUnmarshalInclude) - if !ok { - return errors.New("unmarshal context is not jsonUnmarshalInclude") +func (u *jsonUnmarshaler) unmarshalConfig(unmashalctx *jsonUnmarshalContext) error { + configPath, err := newConfigPath(u.configGraph, unmashalctx.Value) + if err != nil { + return err + } + cache, err := u.configGraph.GetConfig(strings.TrimSpace(configPath.FullPath())) + if err != nil { + return err } - u.completedContext = NewContext(context_type.TypeInclude, unmarshalInclude.GetValue()) + u.completedContext = cache + return nil +} + +func (u *jsonUnmarshaler) unmarshalInclude(unmarshalctx *jsonUnmarshalContext) error { + u.completedContext = NewContext(unmarshalctx.ContextType, unmarshalctx.Value) err := u.completedContext.Error() if err != nil { return err @@ -435,7 +152,7 @@ func (u *jsonUnmarshaler) unmarshalInclude() error { // unmarshal included configs configs := make([]*Config, 0) - for _, childRaw := range unmarshalInclude.GetChildren() { + for _, childRaw := range unmarshalctx.Children { var path string err := json.Unmarshal(*childRaw, &path) if err != nil { @@ -457,63 +174,3 @@ func (u *jsonUnmarshaler) unmarshalInclude() error { // include configs return u.completedContext.(*Include).InsertConfig(configs...) } - -func RegisterJsonRegMatcher(contextType context_type.ContextType, regexp *regexp.Regexp) error { - jsonUnmarshalRegMatcherMap[contextType] = func(jsonraw []byte) bool { - return regexp.Find(jsonraw) != nil - } - return nil -} - -func RegisterJsonUnmarshalerBuilder(contextType context_type.ContextType, newFunc func() JsonUnmarshalContext) error { - jsonUnmarshalerBuilderMap[contextType] = func(graph ConfigGraph, father context.Context) *jsonUnmarshaler { - return &jsonUnmarshaler{ - unmarshalContext: newFunc(), - configGraph: graph, - completedContext: context.NullContext(), - fatherContext: father, - } - } - return nil -} - -func registerJsonRegMatchers() error { - errs := make([]error, 0) - errs = append(errs, - registerCommentJsonRegMatcher(), - registerEventsJsonRegMatcher(), - registerGEOJsonRegMatcher(), - registerHTTPJsonRegMatcher(), - registerIFJsonRegMatcher(), - registerIncludeJsonRegMatcher(), - registerLimitExceptJsonRegMatcher(), - registerLocationJsonRegMatcher(), - registerMapJsonRegMatcher(), - registerServerJsonRegMatcher(), - registerStreamJsonRegMatcher(), - registerTypesJsonRegMatcher(), - registerUpstreamJsonRegMatcher(), - ) - return errors.NewAggregate(errs) -} - -func registerJsonUnmarshalerBuilders() error { - errs := make([]error, 0) - errs = append(errs, - registerCommentJsonUnmarshalerBuilder(), - registerDirectiveJsonUnmarshalerBuilder(), - registerEventsJsonUnmarshalerBuilder(), - registerGEOJsonUnmarshalerBuilder(), - registerHTTPJsonUnmarshalerBuilder(), - registerIFJsonUnmarshalerBuilder(), - registerIncludeJsonUnmarshalerBuilder(), - registerLimitExceptJsonUnmarshalerBuilder(), - registerLocationJsonUnmarshalerBuilder(), - registerMapJsonUnmarshalerBuilder(), - registerServerJsonUnmarshalerBuilder(), - registerStreamJsonUnmarshalerBuilder(), - registerTypesJsonUnmarshalerBuilder(), - registerUpstreamJsonUnmarshalerBuilder(), - ) - return errors.NewAggregate(errs) -} diff --git a/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler_test.go b/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler_test.go index 27ce2eb..f820c94 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/json_unmarshaler_test.go @@ -5,322 +5,9 @@ import ( "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context" "github.com/ClessLi/bifrost/pkg/resolv/V3/nginx/configuration/context_type" "reflect" - "regexp" "testing" ) -func TestRegisterJsonRegMatcher(t *testing.T) { - type args struct { - contextType context_type.ContextType - regexp *regexp.Regexp - } - tests := []struct { - name string - args args - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := RegisterJsonRegMatcher(tt.args.contextType, tt.args.regexp); (err != nil) != tt.wantErr { - t.Errorf("RegisterJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func TestRegisterJsonUnmarshalerBuilder(t *testing.T) { - type args struct { - contextType context_type.ContextType - newFunc func() JsonUnmarshalContext - } - tests := []struct { - name string - args args - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := RegisterJsonUnmarshalerBuilder(tt.args.contextType, tt.args.newFunc); (err != nil) != tt.wantErr { - t.Errorf("RegisterJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_jsonUnmarshalComment_GetChildren(t *testing.T) { - type fields struct { - Comments string - Inline bool - } - tests := []struct { - name string - fields fields - want []*json.RawMessage - }{ - { - name: "return null", - want: []*json.RawMessage{}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - c := jsonUnmarshalComment{ - Comments: tt.fields.Comments, - Inline: tt.fields.Inline, - } - if got := c.GetChildren(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("GetChildren() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalComment_GetValue(t *testing.T) { - type fields struct { - Comments string - Inline bool - } - tests := []struct { - name string - fields fields - want string - }{ - { - name: "null comments", - fields: fields{Comments: ""}, - want: "", - }, - { - name: "some comments", - fields: fields{Comments: " test xxx "}, - want: " test xxx ", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - c := jsonUnmarshalComment{ - Comments: tt.fields.Comments, - Inline: tt.fields.Inline, - } - if got := c.GetValue(); got != tt.want { - t.Errorf("GetValue() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalComment_Type(t *testing.T) { - type fields struct { - Comments string - Inline bool - } - tests := []struct { - name string - fields fields - want context_type.ContextType - }{ - { - name: "inline comment", - fields: fields{Inline: true}, - want: context_type.TypeInlineComment, - }, - { - name: "not inline comment", - fields: fields{Inline: false}, - want: context_type.TypeComment, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - c := jsonUnmarshalComment{ - Comments: tt.fields.Comments, - Inline: tt.fields.Inline, - } - if got := c.Type(); got != tt.want { - t.Errorf("Type() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalContext_GetChildren(t *testing.T) { - type fields struct { - Value string - Children []*json.RawMessage - contextType context_type.ContextType - } - tests := []struct { - name string - fields fields - want []*json.RawMessage - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - u := jsonUnmarshalContext{ - Value: tt.fields.Value, - Children: tt.fields.Children, - contextType: tt.fields.contextType, - } - if got := u.GetChildren(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("GetChildren() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalContext_GetValue(t *testing.T) { - type fields struct { - Value string - Children []*json.RawMessage - contextType context_type.ContextType - } - tests := []struct { - name string - fields fields - want string - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - u := jsonUnmarshalContext{ - Value: tt.fields.Value, - Children: tt.fields.Children, - contextType: tt.fields.contextType, - } - if got := u.GetValue(); got != tt.want { - t.Errorf("GetValue() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalContext_Type(t *testing.T) { - type fields struct { - Value string - Children []*json.RawMessage - contextType context_type.ContextType - } - tests := []struct { - name string - fields fields - want context_type.ContextType - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - u := jsonUnmarshalContext{ - Value: tt.fields.Value, - Children: tt.fields.Children, - contextType: tt.fields.contextType, - } - if got := u.Type(); got != tt.want { - t.Errorf("Type() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalDirective_GetChildren(t *testing.T) { - type fields struct { - Name string - Params string - } - tests := []struct { - name string - fields fields - want []*json.RawMessage - }{ - { - name: "return null", - want: []*json.RawMessage{}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - d := jsonUnmarshalDirective{ - Name: tt.fields.Name, - Params: tt.fields.Params, - } - if got := d.GetChildren(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("GetChildren() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalDirective_GetValue(t *testing.T) { - type fields struct { - Name string - Params string - } - tests := []struct { - name string - fields fields - want string - }{ - { - name: "directive without params", - fields: fields{Name: "server_name"}, - want: "server_name", - }, - { - name: "directive with params", - fields: fields{ - Name: " server_name", - Params: "testserver.com ", - }, - want: "server_name testserver.com", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - d := jsonUnmarshalDirective{ - Name: tt.fields.Name, - Params: tt.fields.Params, - } - if got := d.GetValue(); got != tt.want { - t.Errorf("GetValue() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshalDirective_Type(t *testing.T) { - type fields struct { - Name string - Params string - } - tests := []struct { - name string - fields fields - want context_type.ContextType - }{ - { - name: "directive type", - want: context_type.TypeDirective, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - d := jsonUnmarshalDirective{ - Name: tt.fields.Name, - Params: tt.fields.Params, - } - if got := d.Type(); got != tt.want { - t.Errorf("Type() = %v, want %v", got, tt.want) - } - }) - } -} - func Test_jsonUnmarshaler_UnmarshalJSON(t *testing.T) { testTargetFatherCtx := NewContext(context_type.TypeServer, "") testMain, err := NewMain("C:\\test\\test.conf") @@ -329,10 +16,10 @@ func Test_jsonUnmarshaler_UnmarshalJSON(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -353,7 +40,6 @@ func Test_jsonUnmarshaler_UnmarshalJSON(t *testing.T) { } type fields struct { - unmarshalContext JsonUnmarshalContext configGraph ConfigGraph completedContext context.Context fatherContext context.Context @@ -370,41 +56,97 @@ func Test_jsonUnmarshaler_UnmarshalJSON(t *testing.T) { { name: "normal test", fields: fields{ - unmarshalContext: &jsonUnmarshalLocation{jsonUnmarshalContext{contextType: context_type.TypeLocation}}, configGraph: testMain.graph(), completedContext: context.NullContext(), fatherContext: testTargetFatherCtx, }, args: args{bytes: []byte( - `{"location": - { - "value": "~ /target", - "params": - [ - { - "inline": true, - "comments": "target location" - }, - { - "include": + `{ + "context-type": "location", + "value": "~ /target", + "params": + [ + { + "context-type": "inline_comment", + "value": "target location" + }, + { + "context-type": "include", + "value": "conf.d\\*conf", + "params": + [ + "conf.d\\proxy.conf" + ] + } + ] +}`, + )}, + }, + { + name: "unmarshal config", + fields: fields{ + configGraph: testMain.graph(), + completedContext: context.NullContext(), + fatherContext: testTargetFatherCtx, + }, + args: args{bytes: []byte( + `{ + "context-type": "config", + "value": "conf.d\\proxy.conf", + "params": [ + { + "context-type": "location", + "value": "~ /test_proxy", + "params": [ { - "value": "conf.d\\*conf", - "params": - [ - "conf.d\\proxy.conf" - ] + "context-type": "directive", + "value": "proxy_pass https://baidu.com" } - } - ] - } + ] + }, + { + "context-type": "comment", + "value": "test proxy end" + } + ] +}`, + )}, + }, + { + name: "config with unmatched config path", + fields: fields{ + configGraph: testMain.graph(), + completedContext: context.NullContext(), + fatherContext: testTargetFatherCtx, + }, + args: args{bytes: []byte( + `{ + "context-type": "config", + "value": "conf.d\\proxy.conf1", + "params": [ + { + "context-type": "location", + "value": "~ /test_proxy", + "params": [ + { + "context-type": "directive", + "value": "proxy_pass https://baidu.com" + } + ] + }, + { + "context-type": "comment", + "value": "test proxy end" + } + ] }`, )}, + wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { u := &jsonUnmarshaler{ - unmarshalContext: tt.fields.unmarshalContext, configGraph: tt.fields.configGraph, completedContext: tt.fields.completedContext, fatherContext: tt.fields.fatherContext, @@ -416,615 +158,125 @@ func Test_jsonUnmarshaler_UnmarshalJSON(t *testing.T) { } } -func Test_jsonUnmarshaler_nextUnmarshaler(t *testing.T) { - type fields struct { - unmarshalContext JsonUnmarshalContext - configGraph ConfigGraph - completedContext context.Context - fatherContext context.Context - } - type args struct { - message *json.RawMessage - } - tests := []struct { - name string - fields fields - args args - want *jsonUnmarshaler - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - u := &jsonUnmarshaler{ - unmarshalContext: tt.fields.unmarshalContext, - configGraph: tt.fields.configGraph, - completedContext: tt.fields.completedContext, - fatherContext: tt.fields.fatherContext, - } - if got := u.nextUnmarshaler(tt.args.message); !reflect.DeepEqual(got, tt.want) { - t.Errorf("nextUnmarshaler() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_jsonUnmarshaler_unmarshalInclude(t *testing.T) { - type fields struct { - unmarshalContext JsonUnmarshalContext - configGraph ConfigGraph - completedContext context.Context - fatherContext context.Context - } - tests := []struct { - name string - fields fields - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - u := &jsonUnmarshaler{ - unmarshalContext: tt.fields.unmarshalContext, - configGraph: tt.fields.configGraph, - completedContext: tt.fields.completedContext, - fatherContext: tt.fields.fatherContext, - } - if err := u.unmarshalInclude(); (err != nil) != tt.wantErr { - t.Errorf("unmarshalInclude() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - func Test_mainUnmarshaler_UnmarshalJSON(t *testing.T) { type fields struct { - unmarshalContext *jsonUnmarshalMain - completedMain MainContext + completedMain MainContext } type args struct { bytes []byte } tests := []struct { - name string - fields fields - args args - wantErr bool + name string + fields fields + args args + wantCheckConfigLines []string + wantErr bool }{ { - name: "normal test", - fields: fields{unmarshalContext: new(jsonUnmarshalMain)}, + name: "normal test", args: args{bytes: []byte( `{ "main-config": "C:\\test\\test.conf", "configs": { "C:\\test\\test.conf": - [ - { - "http": + { + "context-type": "config", + "value": "C:\\test\\test.conf", + "params": + [ { + "context-type": "http", "params": [ { - "inline": true, "comments": "test comment" + "context-type": "inline_comment", "value": "test comment" }, { - "server": - { - "params": - [ - { - "directive": "server_name", "params": "testserver" - }, - { - "location": {"value": "~ /test"} - }, - { - "include": - { - "value": "conf.d\\include*conf", - "params": ["conf.d\\include.location1.conf", "conf.d\\include.location2.conf"] - } - } - ] - } + "context-type": "server", + "params": + [ + { + "context-type": "directive", "value": "server_name testserver" + }, + { + "context-type": "location", "value": "~ /test" + }, + { + "context-type": "include", + "value": "conf.d\\include*conf", + "params": ["conf.d\\include.location1.conf", "conf.d\\include.location2.conf"] + } + ] } ] } - } - ], + ] + }, "conf.d\\include.location1.conf": - [ - { - "location": {"value": "~ /test1"} - } - ], + { + "context-type": "config", + "value": "conf.d\\include.location1.conf", + "params": + [ + { + "context-type": "location", "value": "~ /test1" + } + ] + }, "conf.d\\include.location2.conf": - [ - { - "location": {"value": "^~ /test2"} - } - ] + { + "context-type": "config", + "value": "conf.d\\include.location2.conf", + "params": + [ + { + "context-type": "location", "value": "^~ /test2" + } + ] + } } }`, )}, + wantCheckConfigLines: []string{ + "http { # test comment", + " server {", + " server_name testserver;", + " location ~ /test {", + " }", + " # include <== conf.d\\include*conf", + " location ~ /test1 {", + " }", + " location ^~ /test2 {", + " }", + " }", + "}", + }, + wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mainUnmarshaler{ - unmarshalContext: tt.fields.unmarshalContext, - completedMain: tt.fields.completedMain, + completedMain: tt.fields.completedMain, } if err := m.UnmarshalJSON(tt.args.bytes); (err != nil) != tt.wantErr { t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) } + if got, err := m.completedMain.ConfigLines(false); err != nil { + t.Errorf("view unmarshaled main failed, error = %v", err) + } else if !reflect.DeepEqual(got, tt.wantCheckConfigLines) { + t.Errorf("unmarshaled main ConfigLines() = %v, want %v", got, tt.wantCheckConfigLines) + } }) } } -func Test_registerCommentJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerCommentJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerCommentJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerCommentJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerCommentJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerCommentJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerDirectiveJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerDirectiveJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerDirectiveJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerEventsJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerEventsJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerEventsJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerEventsJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerEventsJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerEventsJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerGEOJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerGEOJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerGEOJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerGEOJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerGEOJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerGEOJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerHTTPJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerHTTPJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerHTTPJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerHTTPJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerHTTPJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerHTTPJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerIFJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerIFJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerIFJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerIFJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerIFJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerIFJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerIncludeJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerIncludeJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerIncludeJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerIncludeJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerIncludeJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerIncludeJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerJsonRegMatchers(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerJsonRegMatchers(); (err != nil) != tt.wantErr { - t.Errorf("registerJsonRegMatchers() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerJsonUnmarshalerBuilders(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerJsonUnmarshalerBuilders(); (err != nil) != tt.wantErr { - t.Errorf("registerJsonUnmarshalerBuilders() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerLimitExceptJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerLimitExceptJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerLimitExceptJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerLimitExceptJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerLimitExceptJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerLimitExceptJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerLocationJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerLocationJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerLocationJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerLocationJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerLocationJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerLocationJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerMapJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerMapJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerMapJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerMapJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerMapJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerMapJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerServerJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerServerJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerServerJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerServerJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerServerJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerServerJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerStreamJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerStreamJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerStreamJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerStreamJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerStreamJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerStreamJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerTypesJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerTypesJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerTypesJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerTypesJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerTypesJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerTypesJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerUpstreamJsonRegMatcher(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerUpstreamJsonRegMatcher(); (err != nil) != tt.wantErr { - t.Errorf("registerUpstreamJsonRegMatcher() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_registerUpstreamJsonUnmarshalerBuilder(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := registerUpstreamJsonUnmarshalerBuilder(); (err != nil) != tt.wantErr { - t.Errorf("registerUpstreamJsonUnmarshalerBuilder() error = %v, wantErr %v", err, tt.wantErr) - } - }) +func Test_jsonMarshal(t *testing.T) { + e := NewContext(context_type.TypeEvents, "") + d, err := json.Marshal(e) + if err != nil { + t.Fatal(err) } + t.Log(string(d)) } diff --git a/pkg/resolv/V3/nginx/configuration/context/local/loader.go b/pkg/resolv/V3/nginx/configuration/context/local/loader.go index 71f5492..dbf630d 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/loader.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/loader.go @@ -33,7 +33,7 @@ func (j *jsonLoader) Load() (MainContext, error) { func JsonLoader(data []byte) Loader { return &jsonLoader{ - unmarshaler: &mainUnmarshaler{unmarshalContext: new(jsonUnmarshalMain)}, + unmarshaler: &mainUnmarshaler{}, jsonBytes: data, } } diff --git a/pkg/resolv/V3/nginx/configuration/context/local/loader_test.go b/pkg/resolv/V3/nginx/configuration/context/local/loader_test.go index ec47a48..0faf4dd 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/loader_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/loader_test.go @@ -49,7 +49,7 @@ func TestJsonLoader(t *testing.T) { name: "normal test", args: args{data: []byte("{\"testdata\": \"test\"}")}, want: &jsonLoader{ - unmarshaler: &mainUnmarshaler{unmarshalContext: new(jsonUnmarshalMain)}, + unmarshaler: &mainUnmarshaler{}, jsonBytes: []byte("{\"testdata\": \"test\"}"), }, }, @@ -218,12 +218,12 @@ func Test_fileLoader_Load(t *testing.T) { t.Fatal(err) } simpleMain. - Insert(NewComment("user nobody;", false), 0). - Insert(NewDirective("worker_processes", "1"), 1). - Insert(NewComment("inline comments", true), 2). + Insert(NewContext(context_type.TypeComment, "user nobody;"), 0). + Insert(NewContext(context_type.TypeDirective, "worker_processes 1"), 1). + Insert(NewContext(context_type.TypeInlineComment, "inline comments"), 2). Insert( NewContext(context_type.TypeEvents, ""). - Insert(NewDirective("worker_connections", "1024"), 0), + Insert(NewContext(context_type.TypeDirective, "worker_connections 1024"), 0), 3, ) type fields struct { diff --git a/pkg/resolv/V3/nginx/configuration/context/local/main_context_test.go b/pkg/resolv/V3/nginx/configuration/context/local/main_context_test.go index c0a7d20..624f992 100644 --- a/pkg/resolv/V3/nginx/configuration/context/local/main_context_test.go +++ b/pkg/resolv/V3/nginx/configuration/context/local/main_context_test.go @@ -189,7 +189,7 @@ func TestMain_Insert(t *testing.T) { name: "return main context itself", fields: testMain, args: args{ - ctx: NewDirective("test", ""), + ctx: NewContext(context_type.TypeDirective, "test"), idx: 0, }, want: testMain, @@ -242,10 +242,10 @@ func TestMain_MarshalJSON(t *testing.T) { } testMain.Insert( NewContext(context_type.TypeHttp, ""). - Insert(NewComment("test comment", true), 0). + Insert(NewContext(context_type.TypeInlineComment, "test comment"), 0). Insert( NewContext(context_type.TypeServer, ""). - Insert(NewDirective("server_name", "testserver"), 0). + Insert(NewContext(context_type.TypeDirective, "server_name testserver"), 0). Insert( NewContext(context_type.TypeLocation, "~ /test"), 1, @@ -283,26 +283,14 @@ func TestMain_MarshalJSON(t *testing.T) { { name: "empty main", fields: fields{ConfigGraph: emptyMain.graph()}, - want: []byte(`{"main-config":"C:\\test\\test.conf","configs":{"C:\\test\\test.conf":[]}}`), + want: []byte(`{"main-config":"C:\\test\\test.conf","configs":{"C:\\test\\test.conf":{"context-type":"config","value":"C:\\test\\test.conf"}}}`), wantErr: false, }, { name: "normal test", fields: fields{ConfigGraph: testMain.graph()}, want: []byte( - `{"main-config":"C:\\test\\test.conf",` + - `"configs":{"C:\\test\\test.conf":[{` + - `"http":{"params":[{"comments":"test comment","inline":true},` + - `{"server":{"params":[{"directive":"server_name","params":"testserver"},` + - `{"location":{"value":"~ /test"}},` + - `{"include":{"value":"conf.d\\include*conf","params":["conf.d\\include.location1.conf","conf.d\\include.location2.conf"]}}` + - `]}}` + - `]}` + - `}],` + - `"conf.d\\include.location1.conf":[{"location":{"value":"~ /test1"}}],` + - `"conf.d\\include.location2.conf":[{"location":{"value":"^~ /test2"}}]` + - `}` + - `}`, + `{"main-config":"C:\\test\\test.conf","configs":{"C:\\test\\test.conf":{"context-type":"config","value":"C:\\test\\test.conf","params":[{"context-type":"http","params":[{"context-type":"inline_comment","value":"test comment"},{"context-type":"server","params":[{"context-type":"directive","value":"server_name testserver"},{"context-type":"location","value":"~ /test"},{"context-type":"include","value":"conf.d\\include*conf","params":["conf.d\\include.location1.conf","conf.d\\include.location2.conf"]}]}]}]},"conf.d\\include.location1.conf":{"context-type":"config","value":"conf.d\\include.location1.conf","params":[{"context-type":"location","value":"~ /test1"}]},"conf.d\\include.location2.conf":{"context-type":"config","value":"conf.d\\include.location2.conf","params":[{"context-type":"location","value":"^~ /test2"}]}}}`, ), wantErr: false, }, @@ -352,7 +340,7 @@ func TestMain_Modify(t *testing.T) { name: "return main context itself", fields: testMain, args: args{ - ctx: NewDirective("test", ""), + ctx: NewContext(context_type.TypeDirective, "test"), idx: 0, }, want: testMain, diff --git a/pkg/resolv/V3/nginx/configuration/nginx_config_test.go b/pkg/resolv/V3/nginx/configuration/nginx_config_test.go index 2f181a4..6a9eb04 100644 --- a/pkg/resolv/V3/nginx/configuration/nginx_config_test.go +++ b/pkg/resolv/V3/nginx/configuration/nginx_config_test.go @@ -237,52 +237,61 @@ func Test_nginxConfig_UpdateFromJsonBytes(t *testing.T) { "configs": { "C:\\test\\test.conf": - [ - { - "http": + { + "context-type": "config", + "value": "C:\\test\\test.conf", + "params": + [ { + "context-type": "http", "params": [ { - "inline": true, "comments": "test comment" + "context-type": "inline_comment", "value": "test comment" }, { - "server": - { - "params": - [ - { - "directive": "server_name", "params": "testserver" - }, - { - "location": {"value": "~ /test"} - }, - { - "include": - { - "value": "conf.d\\include*conf", - "params": ["conf.d\\include.location1.conf", "conf.d\\include.location2.conf"] - } - } - ] - } + "context-type": "server", + "params": + [ + { + "context-type": "directive", "value": "server_name testserver" + }, + { + "context-type": "location", "value": "~ /test" + }, + { + "context-type": "include", + "value": "conf.d\\include*conf", + "params": ["conf.d\\include.location1.conf", "conf.d\\include.location2.conf"] + } + ] } ] } - } - ], + ] + }, "conf.d\\include.location1.conf": - [ - { - "location": {"value": "~ /test1"} - } - ], + { + "context-type": "config", + "value": "conf.d\\include.location1.conf", + "params": + [ + { + "context-type": "location", "value": "~ /test1" + } + ] + }, "conf.d\\include.location2.conf": - [ - { - "location": {"value": "^~ /test2"} - } - ] + { + "context-type": "config", + "value": "conf.d\\include.location2.conf", + "params": + [ + { + "context-type": "location", "value": "^~ /test2" + } + ] + } } }`, )}, diff --git a/test/grpc_client/bifrost/client_test.go b/test/grpc_client/bifrost/client_test.go index 68cdc9c..52a18a9 100644 --- a/test/grpc_client/bifrost/client_test.go +++ b/test/grpc_client/bifrost/client_test.go @@ -190,7 +190,7 @@ func TestBifrostClientOperation(t *testing.T) { ctx, idx := server.QueryByKeyWords(nginx_ctx.NewKeyWords(context_type.TypeLocation).SetRegexpMatchingValue(`^/test1-location$`)).Target(). QueryByKeyWords(nginx_ctx.NewKeyWords(context_type.TypeIf).SetRegexpMatchingValue(`^\(\$http_api_name != ''\)$`)).Target(). QueryByKeyWords(nginx_ctx.NewKeyWords(context_type.TypeDirective).SetStringMatchingValue("proxy_pass")).Position() - err = ctx.Insert(local.NewComment(fmt.Sprintf("[%s]test comments", time.Now().String()), true), idx+1).Error() + err = ctx.Insert(local.NewContext(context_type.TypeInlineComment, fmt.Sprintf("[%s]test comments", time.Now().String())), idx+1).Error() if err != nil { t.Fatal(err) }