1 Star 0 Fork 0

me/gbase

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
base.go 1.89 KB
一键复制 编辑 原始数据 按行查看 历史
cc 提交于 2025-01-03 11:53 . cc-add base.fromxml
package gbase
import (
"encoding/xml"
"github.com/cloudwego/hertz/pkg/app/server/binding"
jsoniter "github.com/json-iterator/go"
"strings"
)
// 全局基类
type Base struct { /*这里不能写字段名*/
}
func (this *Base) ToString(child any) string {
str, _ := jsoniter.MarshalToString(child)
return str
}
func (this *Base) ToBytes(child any) []byte {
bytes, _ := jsoniter.Marshal(child)
return bytes
}
func (this *Base) ToMap(child any) (cm Map) {
cm = Map{}
_ = cm.FromX(child)
return
}
func (this *Base) ToMapExclude(child any, keys ...string) (cm Map) {
return this.ToMap(child).RemoveKeys(keys...)
}
func (this *Base) ToMapInclude(child any, keys ...string) (cm Map) {
all := this.ToMap(child)
cm = Map{}
for _, v := range keys {
if all.Exist(v) {
cm[v] = all[v]
}
}
return
}
func (this *Base) FromForm(child any, formStr string) (err error) {
list := strings.Split(formStr, "&")
m := make(map[any]any)
if len(list) > 0 {
for _, v := range list {
cur := strings.Split(v, "=")
if len(cur) == 2 {
m[cur[0]] = cur[1]
}
}
}
if len(m) > 0 {
if bytes, err := jsoniter.Marshal(m); err != nil {
return err
} else {
if err = jsoniter.Unmarshal(bytes, child); err != nil {
return err
}
}
}
return
}
// from string,[]byte,map,struct
func (this *Base) FromX(child any, params any) error {
var (
jsonBytes []byte
err error
//jsonStr string
)
switch params.(type) {
case string:
jsonBytes = String(params.(string)).ToBytes()
case []byte:
//do nothing
jsonBytes = params.([]byte)
default:
if jsonBytes, err = jsoniter.Marshal(params); err != nil {
return err
}
}
if err = jsoniter.Unmarshal(jsonBytes, child); err != nil {
return err
}
return nil
}
func (this *Base) FromXml(child any, xmlStr string) error {
return xml.Unmarshal([]byte(xmlStr), child)
}
func (this *Base) Vd(child any) error {
return binding.Validate(child)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/851537/gbase.git
git@gitee.com:851537/gbase.git
851537
gbase
gbase
master

搜索帮助