100 lines
2.2 KiB
Go
100 lines
2.2 KiB
Go
// Package rpc ...
|
|
//
|
|
// Description : rpc ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2022-06-30 18:33c
|
|
package rpc
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/tidwall/gjson"
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// parseResponseBody 解析响应body, 支持 json + xml + ini + yaml
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 18:36 2022/6/30
|
|
func parseResponseBody(responseType string, body []byte, receiver interface{}) error {
|
|
responseType = strings.ToLower(responseType)
|
|
if strings.Contains(responseType, "json") {
|
|
return parser.ParseJSON(body, receiver)
|
|
}
|
|
if strings.Contains(responseType, "xml") {
|
|
return parser.ParseXml(body, receiver)
|
|
}
|
|
if strings.Contains(responseType, "yaml") || strings.Contains(responseType, "yml") {
|
|
return parser.ParseYaml(body, receiver)
|
|
}
|
|
if strings.Contains(responseType, "ini") {
|
|
return parser.ParseIni(body, receiver)
|
|
}
|
|
|
|
// 适配 text/plan
|
|
if strings.Contains(responseType, "plain") {
|
|
if !gjson.Valid(string(body)) {
|
|
return errors.New("text/plain 类型数据仅支持通过JSON解析")
|
|
}
|
|
return parser.ParseJSON(body, receiver)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var parser *result
|
|
|
|
func init() {
|
|
parser = &result{}
|
|
parser = &result{}
|
|
}
|
|
|
|
type result struct {
|
|
}
|
|
|
|
// ParseJSON 解析JSON数据
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 18:34 2022/6/30
|
|
func (r *result) ParseJSON(inputContent []byte, receiver interface{}) error {
|
|
decoder := json.NewDecoder(bytes.NewReader(inputContent))
|
|
decoder.UseNumber()
|
|
return decoder.Decode(receiver)
|
|
}
|
|
|
|
// ParseYaml 解析yaml数据
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 18:34 2022/6/30
|
|
func (r *result) ParseYaml(inputContent []byte, receiver interface{}) error {
|
|
decoder := yaml.NewDecoder(bytes.NewReader(inputContent))
|
|
return decoder.Decode(receiver)
|
|
}
|
|
|
|
// ParseXml 解析xml数据
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 18:35 2022/6/30
|
|
func (r *result) ParseXml(inputContent []byte, receiver interface{}) error {
|
|
return xml.Unmarshal(inputContent, receiver)
|
|
}
|
|
|
|
// ParseIni 解析ini
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 11:11 2022/7/1
|
|
func (r *result) ParseIni(inputContent []byte, receiver interface{}) error {
|
|
|
|
return nil
|
|
}
|