From ed479e2a13246ffa268bd248c73bdb26c1e7d3fc Mon Sep 17 00:00:00 2001 From: Jack Date: Tue, 11 Aug 2020 23:20:22 +0800 Subject: [PATCH] improve package gjson for automatic content type checking --- encoding/gjson/gjson_api_new_load.go | 11 +++++++--- encoding/gjson/gjson_z_unit_internal_test.go | 23 ++++++++++++-------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index 52a5374d7..9320a2b0a 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -200,16 +200,21 @@ func LoadContent(data interface{}, safe ...bool) (*Json, error) { } // checkDataType automatically checks and returns the data type for . +// Note that it uses regular expression for loose checking, you can use LoadXXX +// functions to load the content for certain content type. func checkDataType(content []byte) string { if json.Valid(content) { return "json" } else if gregex.IsMatch(`^<.+>[\S\s]+<.+>$`, content) { return "xml" - } else if gregex.IsMatch(`^[\s\t]*[\w\-]+\s*:\s*.+`, content) || gregex.IsMatch(`\n[\s\t]*[\w\-]+\s*:\s*.+`, content) { + } else if gregex.IsMatch(`[\s\t\n]*[\w\-]+\s*:\s*.+`, content) { return "yml" - } else if (gregex.IsMatch(`^[\s\t\[*\]].?*[\w\-]+\s*=\s*.+`, content) || gregex.IsMatch(`\n[\s\t\[*\]]*[\w\-]+\s*=\s*.+`, content)) && gregex.IsMatch(`\n[\s\t]*[\w\-]+\s*=*\"*.+\"`, content) == false && gregex.IsMatch(`^[\s\t]*[\w\-]+\s*=*\"*.+\"`, content) == false { + } else if gregex.IsMatch(`\[[\w]+\]`, content) && + gregex.IsMatch(`[\s\t\n\[\]]*[\w\-]+\s*=\s*.+`, content) && + !gregex.IsMatch(`[\s\t\n]*[\w\-]+\s*=*\"*.+\"`, content) { + // Must contain "[xxx]" section. return "ini" - } else if gregex.IsMatch(`^[\s\t]*[\w\-\."]+\s*=\s*.+`, content) || gregex.IsMatch(`\n[\s\t]*[\w\-\."]+\s*=\s*.+`, content) { + } else if gregex.IsMatch(`[\s\t\n]*[\w\-\."]+\s*=\s*.+`, content) { return "toml" } else { return "" diff --git a/encoding/gjson/gjson_z_unit_internal_test.go b/encoding/gjson/gjson_z_unit_internal_test.go index 1520437a6..2c0e70e51 100644 --- a/encoding/gjson/gjson_z_unit_internal_test.go +++ b/encoding/gjson/gjson_z_unit_internal_test.go @@ -6,12 +6,17 @@ package gjson -//func Test_Load_YAML3(t *testing.T) { -// data := []byte(` -//bb = """ -// dig := dig; END;""" -//`) -// gtest.C(t, func(t *gtest.T) { -// t.Assert(checkDataType(data), "toml") -// }) -//} +import ( + "github.com/gogf/gf/test/gtest" + "testing" +) + +func Test_checkDataType(t *testing.T) { + data := []byte(` +bb = """ + dig := dig; END;""" +`) + gtest.C(t, func(t *gtest.T) { + t.Assert(checkDataType(data), "toml") + }) +}