优化结构

This commit is contained in:
Yvan
2026-08-28 11:10:57 +08:00
parent 5b17f47141
commit 676fa4d952
10 changed files with 91 additions and 80 deletions
-26
View File
@@ -15,14 +15,6 @@ func JSONObject(raw []byte) map[string]any {
return object
}
func NestedString(value any, keys ...string) string {
found := nestedValue(value, keys...)
if found == nil {
return ""
}
return strings.TrimSpace(fmt.Sprint(found))
}
func StringAtPath(value any, path string) string {
found := ValueAtPath(value, path)
if found == nil {
@@ -46,21 +38,3 @@ func ValueAtPath(value any, path string) any {
}
return current
}
func nestedValue(value any, keys ...string) any {
object, ok := value.(map[string]any)
if !ok {
return nil
}
for _, key := range keys {
if found, exists := object[key]; exists && found != nil && fmt.Sprint(found) != "" {
return found
}
}
for _, nestedKey := range []string{"data", "result", "order", "transaction", "response"} {
if found := nestedValue(object[nestedKey], keys...); found != nil {
return found
}
}
return nil
}
+3 -3
View File
@@ -2,10 +2,10 @@ package paymentkit
import "testing"
func TestNestedAndPathValues(t *testing.T) {
func TestJSONObjectAndPathValues(t *testing.T) {
object := JSONObject([]byte(`{"data":{"status":"SUCCESS","amount":100}}`))
if got := NestedString(object, "status"); got != "SUCCESS" {
t.Fatalf("NestedString = %q", got)
if object == nil {
t.Fatal("JSONObject returned nil")
}
if got := StringAtPath(object, "data.amount"); got != "100" {
t.Fatalf("StringAtPath = %q", got)
-60
View File
@@ -1,60 +0,0 @@
package paymentkit
import (
"bytes"
"encoding/xml"
"io"
"sort"
"strings"
)
type xmlValue struct {
XMLName xml.Name
Value string `xml:",chardata"`
}
func XMLValues(raw []byte) (map[string]string, error) {
decoder := xml.NewDecoder(bytes.NewReader(raw))
result := map[string]string{}
for {
token, err := decoder.Token()
if err == io.EOF {
return result, nil
}
if err != nil {
return nil, err
}
start, ok := token.(xml.StartElement)
if !ok || start.Name.Local == "xml" {
continue
}
var value xmlValue
if err = decoder.DecodeElement(&value, &start); err != nil {
return nil, err
}
if value.Value != "" {
result[start.Name.Local] = value.Value
}
}
}
func XMLEncode(values map[string]string) []byte {
var b strings.Builder
b.WriteString("<xml>")
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
b.WriteString("<")
b.WriteString(key)
b.WriteString("><![CDATA[")
b.WriteString(values[key])
b.WriteString("]]></")
b.WriteString(key)
b.WriteString(">")
}
b.WriteString("</xml>")
return []byte(b.String())
}