improve package gjson for automatic content type checking

This commit is contained in:
Jack 2020-08-11 23:20:22 +08:00
parent 19937cb75d
commit ed479e2a13
2 changed files with 22 additions and 12 deletions

View File

@ -200,16 +200,21 @@ func LoadContent(data interface{}, safe ...bool) (*Json, error) {
} }
// checkDataType automatically checks and returns the data type for <content>. // checkDataType automatically checks and returns the data type for <content>.
// 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 { func checkDataType(content []byte) string {
if json.Valid(content) { if json.Valid(content) {
return "json" return "json"
} else if gregex.IsMatch(`^<.+>[\S\s]+<.+>$`, content) { } else if gregex.IsMatch(`^<.+>[\S\s]+<.+>$`, content) {
return "xml" 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" 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" 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" return "toml"
} else { } else {
return "" return ""

View File

@ -6,12 +6,17 @@
package gjson package gjson
//func Test_Load_YAML3(t *testing.T) { import (
// data := []byte(` "github.com/gogf/gf/test/gtest"
//bb = """ "testing"
// dig := dig; END;""" )
//`)
// gtest.C(t, func(t *gtest.T) { func Test_checkDataType(t *testing.T) {
// t.Assert(checkDataType(data), "toml") data := []byte(`
// }) bb = """
//} dig := dig; END;"""
`)
gtest.C(t, func(t *gtest.T) {
t.Assert(checkDataType(data), "toml")
})
}