mirror of
https://github.com/antlabs/tostruct.git
synced 2025-12-24 12:58:04 +08:00
从json, yaml字符串生成protobuf
This commit is contained in:
@@ -5,8 +5,11 @@ package json
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var ErrValid = errors.New("valid json")
|
||||
|
||||
func Valid[T string | []byte](t T) bool {
|
||||
var x interface{} = t
|
||||
|
||||
@@ -30,3 +33,17 @@ func Valid[T string | []byte](t T) bool {
|
||||
|
||||
return json.Valid(b)
|
||||
}
|
||||
|
||||
func ValidAndUnmarshal(b []byte) (o map[string]any, a []any, err error) {
|
||||
if !Valid(b) {
|
||||
return nil, nil, ErrValid
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(b, &o); err == nil /*没有错误说明是json 对象字符串*/ {
|
||||
return o, nil, ErrValid
|
||||
}
|
||||
|
||||
// 可能是array对象
|
||||
err = json.Unmarshal(b, &a)
|
||||
return nil, a, err
|
||||
}
|
||||
|
||||
@@ -3,13 +3,32 @@ package protobuf
|
||||
import (
|
||||
"github.com/antlabs/tostruct/json"
|
||||
"github.com/antlabs/tostruct/option"
|
||||
"github.com/antlabs/tostruct/yaml"
|
||||
)
|
||||
|
||||
type Type interface {
|
||||
map[string]any | []any
|
||||
map[string]any | []any | []byte
|
||||
}
|
||||
|
||||
func Marshal[T Type](t T, opt ...option.OptionFunc) (b []byte, err error) {
|
||||
i := any(t)
|
||||
switch v := i.(type) {
|
||||
case []byte:
|
||||
o, a, err := json.ValidAndUnmarshal(v)
|
||||
if err != nil {
|
||||
o, a, err = yaml.Unmarshal(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if o != nil {
|
||||
return json.Marshal(o, append(opt, option.WithProtobuf())...)
|
||||
}
|
||||
|
||||
if a != nil {
|
||||
return json.Marshal(a, append(opt, option.WithProtobuf())...)
|
||||
}
|
||||
}
|
||||
|
||||
return json.Marshal(t, append(opt, option.WithProtobuf())...)
|
||||
}
|
||||
|
||||
21
yaml/yaml.go
21
yaml/yaml.go
@@ -8,19 +8,28 @@ import (
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func Marshal(bytes []byte, opt ...option.OptionFunc) (b []byte, err error) {
|
||||
var o map[string]any
|
||||
var a []any
|
||||
func Unmarshal(bytes []byte) (o map[string]any, a []any, err error) {
|
||||
|
||||
err = yaml.Unmarshal(bytes, &o)
|
||||
if err != nil {
|
||||
if err = yaml.Unmarshal(bytes, &a); err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
return json.Marshal(a, opt...)
|
||||
func Marshal(bytes []byte, opt ...option.OptionFunc) (b []byte, err error) {
|
||||
|
||||
o, a, err := Unmarshal(bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
opt = append(opt, option.WithTagName("yaml"))
|
||||
return json.Marshal(o, opt...)
|
||||
if o != nil {
|
||||
return json.Marshal(o, opt...)
|
||||
}
|
||||
|
||||
return json.Marshal(a, opt...)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user