perf: add auto format detect for `yaml` and `xml`

This commit is contained in:
Lykin 2024-01-30 01:30:44 +08:00
parent 74d789ac8e
commit 7faca878a3
3 changed files with 57 additions and 0 deletions

View File

@ -14,6 +14,8 @@ type DataConvert interface {
var (
jsonConv JsonConvert
yamlConv YamlConvert
xmlConv XmlConvert
base64Conv Base64Convert
binaryConv BinaryConvert
hexConv HexConvert
@ -197,6 +199,16 @@ func autoViewAs(str string) (value, resultFormat string) {
return
}
if value, ok = yamlConv.Decode(str); ok {
resultFormat = types.FORMAT_YAML
return
}
if value, ok = xmlConv.Decode(str); ok {
resultFormat = types.FORMAT_XML
return
}
if strutil.ContainsBinary(str) {
if value, ok = hexConv.Decode(str); ok {
resultFormat = types.FORMAT_HEX

View File

@ -0,0 +1,22 @@
package convutil
import (
"encoding/xml"
"strings"
)
type XmlConvert struct{}
func (XmlConvert) Encode(str string) (string, bool) {
return str, true
}
func (XmlConvert) Decode(str string) (string, bool) {
trimedStr := strings.TrimSpace(str)
if !strings.HasPrefix(trimedStr, "<") && !strings.HasSuffix(trimedStr, ">") {
return str, false
}
var obj any
err := xml.Unmarshal([]byte(trimedStr), &obj)
return str, err == nil
}

View File

@ -0,0 +1,23 @@
package convutil
import (
"gopkg.in/yaml.v3"
"log"
)
type YamlConvert struct{}
func (YamlConvert) Encode(str string) (string, bool) {
return str, true
}
func (YamlConvert) Decode(str string) (string, bool) {
var obj map[string]any
err := yaml.Unmarshal([]byte(str), &obj)
if err != nil {
log.Println(err.Error())
} else {
log.Println(obj)
}
return str, err == nil
}