You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.4 KiB

2 years ago
package form
import (
"git.diulo.com/mogfee/kit/encoding"
"github.com/go-playground/form"
"net/url"
"reflect"
2 years ago
"google.golang.org/protobuf/proto"
2 years ago
)
const (
2 years ago
// Name is form codec name
Name = "x-www-form-urlencoded"
// Null value string
2 years ago
nullStr = "null"
)
var (
encoder = form.NewEncoder()
decoder = form.NewDecoder()
)
func init() {
decoder.SetTagName("json")
encoder.SetTagName("json")
2 years ago
encoding.RegisterCodec(codec{encoder: encoder, decoder: decoder})
2 years ago
}
type codec struct {
encoder *form.Encoder
decoder *form.Decoder
}
2 years ago
func (c codec) Marshal(v interface{}) ([]byte, error) {
2 years ago
var vs url.Values
var err error
if m, ok := v.(proto.Message); ok {
vs, err = EncodeValues(m)
if err != nil {
return nil, err
}
} else {
vs, err = c.encoder.Encode(v)
if err != nil {
return nil, err
}
}
for k, v := range vs {
if len(v) == 0 {
delete(vs, k)
}
}
2 years ago
return []byte(vs.Encode()), nil
2 years ago
}
2 years ago
func (c codec) Unmarshal(data []byte, v interface{}) error {
2 years ago
vs, err := url.ParseQuery(string(data))
if err != nil {
return err
}
2 years ago
2 years ago
rv := reflect.ValueOf(v)
2 years ago
for rv.Kind() == reflect.Ptr {
2 years ago
if rv.IsNil() {
rv.Set(reflect.New(rv.Type().Elem()))
}
rv = rv.Elem()
}
if m, ok := v.(proto.Message); ok {
return DecodeValues(m, vs)
}
if m, ok := rv.Interface().(proto.Message); ok {
return DecodeValues(m, vs)
}
2 years ago
2 years ago
return c.decoder.Decode(v, vs)
}
2 years ago
func (codec) Name() string {
2 years ago
return Name
}