Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

我多加了一个单元,回调解码用,供参考 #10

Open
Leadrive opened this issue Oct 7, 2018 · 1 comment
Open

我多加了一个单元,回调解码用,供参考 #10

Leadrive opened this issue Oct 7, 2018 · 1 comment

Comments

@Leadrive
Copy link

Leadrive commented Oct 7, 2018

从另外一个项目抄过来的。

package wxpay

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"io"
)

// ToJSON 转化成JSON字符
func (p Params) ToJSON() string {
	mjson, _ := json.Marshal(p)
	return string(mjson)
}

// Decode XML解码
func Decode(r io.Reader) Params {
	var (
		d      *xml.Decoder
		start  *xml.StartElement
		params Params
	)
	d = xml.NewDecoder(r)
	params = make(Params)
	for {
		tok, err := d.Token()
		if err != nil {
			break
		}
		switch t := tok.(type) {
		case xml.StartElement:
			start = &t
		case xml.CharData:
			if t = bytes.TrimSpace(t); len(t) > 0 {
				params.SetString(start.Name.Local, string(t))
			}
		}
	}
	return params
}

// Encode XML编码
func Encode(params Params) io.Reader {
	var buf bytes.Buffer
	buf.WriteString(``)
	for k, v := range params {
		buf.WriteString(`<`)
		buf.WriteString(k)
		buf.WriteString(`>`)
	}
	buf.WriteString(``)
	return &buf
}
@neefrankie
Copy link

这个更严谨,XmlToMap()有时候解析到的微信回调数据是空值,可能是换行空格引起的。

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants