add codec option

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2024-09-16 23:02:45 +03:00
parent eb1482d789
commit 3aaf1182cb
2 changed files with 13 additions and 33 deletions

View File

@ -1,5 +1,5 @@
// Package codec is an interface for encoding messages // Package codec is an interface for encoding messages
package codec // import "go.unistack.org/micro/v3/codec" package codec
import ( import (
"errors" "errors"
@ -13,8 +13,6 @@ var (
) )
var ( var (
// DefaultMaxMsgSize specifies how much data codec can handle
DefaultMaxMsgSize = 1024 * 1024 * 4 // 4Mb
// DefaultCodec is the global default codec // DefaultCodec is the global default codec
DefaultCodec = NewCodec() DefaultCodec = NewCodec()
// DefaultTagName specifies struct tag name to control codec Marshal/Unmarshal // DefaultTagName specifies struct tag name to control codec Marshal/Unmarshal
@ -28,21 +26,10 @@ type Codec interface {
String() string String() string
} }
// MarshalAppend calls codec.Marshal(v) and returns the data appended to buf. type CodecV2 interface {
// If codec implements MarshalAppend, that is called instead. Marshal(buf []byte, v interface{}, opts ...Option) ([]byte, error)
func MarshalAppend(buf []byte, c Codec, v interface{}, opts ...Option) ([]byte, error) { Unmarshal(buf []byte, v interface{}, opts ...Option) error
if nc, ok := c.(interface { String() string
MarshalAppend([]byte, interface{}, ...Option) ([]byte, error)
}); ok {
return nc.MarshalAppend(buf, v, opts...)
}
mbuf, err := c.Marshal(v, opts...)
if err != nil {
return nil, err
}
return append(buf, mbuf...), nil
} }
// RawMessage is a raw encoded JSON value. // RawMessage is a raw encoded JSON value.

View File

@ -23,15 +23,8 @@ type Options struct {
Context context.Context Context context.Context
// TagName specifies tag name in struct to control codec // TagName specifies tag name in struct to control codec
TagName string TagName string
// MaxMsgSize specifies max messages size that reads by codec // Flatten specifies that struct must be analyzed for flatten tag
MaxMsgSize int Flatten bool
}
// MaxMsgSize sets the max message size
func MaxMsgSize(n int) Option {
return func(o *Options) {
o.MaxMsgSize = n
}
} }
// TagName sets the codec tag name in struct // TagName sets the codec tag name in struct
@ -65,12 +58,12 @@ func Meter(m meter.Meter) Option {
// NewOptions returns new options // NewOptions returns new options
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
options := Options{ options := Options{
Context: context.Background(), Context: context.Background(),
Logger: logger.DefaultLogger, Logger: logger.DefaultLogger,
Meter: meter.DefaultMeter, Meter: meter.DefaultMeter,
Tracer: tracer.DefaultTracer, Tracer: tracer.DefaultTracer,
MaxMsgSize: DefaultMaxMsgSize, TagName: DefaultTagName,
TagName: DefaultTagName, Flatten: false,
} }
for _, o := range opts { for _, o := range opts {