rpc/result.go

99 lines
2.2 KiB
Go
Raw Normal View History

2022-06-30 18:47:11 +08:00
// Package rpc ...
//
// Description : rpc ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-06-30 18:33c
2022-06-30 18:47:11 +08:00
package rpc
import (
2022-06-30 21:51:49 +08:00
"bytes"
"encoding/json"
2022-07-01 11:12:28 +08:00
"encoding/xml"
"errors"
"strings"
2022-07-01 11:12:28 +08:00
"github.com/tidwall/gjson"
"gopkg.in/yaml.v2"
)
2022-06-30 18:47:11 +08:00
// 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
2022-07-01 11:12:28 +08:00
if strings.Contains(responseType, "plain") {
if !gjson.Valid(string(body)) {
return errors.New("text/plain 类型数据仅支持通过JSON解析")
}
return parser.ParseJSON(body, receiver)
}
2022-06-30 18:47:11 +08:00
return nil
}
var parser *result
2022-07-01 11:12:28 +08:00
func init() {
parser = &result{}
parser = &result{}
}
2022-06-30 18:47:11 +08:00
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 {
2022-06-30 21:51:49 +08:00
decoder := json.NewDecoder(bytes.NewReader(inputContent))
decoder.UseNumber()
return decoder.Decode(receiver)
2022-06-30 18:47:11 +08:00
}
// ParseYaml 解析yaml数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:34 2022/6/30
func (r *result) ParseYaml(inputContent []byte, receiver interface{}) error {
2022-07-01 11:12:28 +08:00
decoder := yaml.NewDecoder(bytes.NewReader(inputContent))
return decoder.Decode(receiver)
2022-06-30 18:47:11 +08:00
}
// ParseXml 解析xml数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:35 2022/6/30
func (r *result) ParseXml(inputContent []byte, receiver interface{}) error {
2022-07-01 11:12:28 +08:00
return xml.Unmarshal(inputContent, receiver)
2022-06-30 18:47:11 +08:00
}
2022-07-01 11:12:28 +08:00
// ParseIni 解析ini
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:11 2022/7/1
2022-06-30 18:47:11 +08:00
func (r *result) ParseIni(inputContent []byte, receiver interface{}) error {
return nil
}