encoding

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2022 License: MIT Imports: 1 Imported by: 1

README

encoding

CI codecov

The Codec interface to unify the serialization/deserialization logic for processing requests.

Fork From https://github.com/go-kratos/kratos/tree/main/encoding

Features

  • dotenv
  • form
  • json
  • protobuf
  • xml
  • yaml

Install

go get github.com/sraphs/encoding
Interface

You should implement the following Codec interface for your custom codec.

// Codec interface is for serialization and deserialization, notice that these methods must be thread-safe.
type Codec interface {
    Marshal(v interface{}) ([]byte, error)
    Unmarshal(data []byte, v interface{}) error
    Name() string
}

Usage

Serialization
// You should manually import this package if you use it directly: 
// import _ "github.com/sraphs/encoding/encoding/json"
jsonCodec := encoding.GetCodec("json")
type user struct {
    Name string
    Age string
    state bool
}
u := &user{
    Name:  "sraph",
    Age:   "2",
    state: false,
}
bytes, _ := jsonCodec.Marshal(u)
fmt.Println(string(bytes))
// output {"Name":"sraph","Age":"2"}
Deserialization
// You should manually import this package if you use it directly: 
// import _ "github.com/sraphs/encoding/encoding/json"
jsonCodec := encoding.GetCodec("json")
type user struct {
    Name string
    Age string
    state bool
}
u := &user{}
jsonCodec.Unmarshal([]byte(`{"Name":"kratos","Age":"2"}`), &u)
fmt.Println(*u)
//output &{kratos 2 false}

Example of Codec Implementation

// https://github.com/sraphs/encoding/blob/main/json/json.go
package json

import (
	"encoding/json"
	"reflect"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"

	"github.com/sraphs/encoding"
)

// Name is the name registered for the json codec.
const Name = "json"

var (
	// MarshalOptions is a configurable JSON format marshaller.
	MarshalOptions = protojson.MarshalOptions{
		EmitUnpopulated: true,
	}
	// UnmarshalOptions is a configurable JSON format parser.
	UnmarshalOptions = protojson.UnmarshalOptions{
		DiscardUnknown: true,
	}
)

func init() {
	encoding.RegisterCodec(codec{})
}

// codec is a Codec implementation with json.
type codec struct{}

func (codec) Marshal(v interface{}) ([]byte, error) {
	switch m := v.(type) {
	case json.Marshaler:
		return m.MarshalJSON()
	case proto.Message:
		return MarshalOptions.Marshal(m)
	default:
		return json.Marshal(m)
	}
}

func (codec) Unmarshal(data []byte, v interface{}) error {
	switch m := v.(type) {
	case json.Unmarshaler:
		return m.UnmarshalJSON(data)
	case proto.Message:
		return UnmarshalOptions.Unmarshal(data, m)
	default:
		rv := reflect.ValueOf(v)
		for rv := rv; rv.Kind() == reflect.Ptr; {
			if rv.IsNil() {
				rv.Set(reflect.New(rv.Type().Elem()))
			}
			rv = rv.Elem()
		}
		if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
			return UnmarshalOptions.Unmarshal(data, m)
		}
		return json.Unmarshal(data, m)
	}
}

func (codec) Name() string {
	return Name
}

Contributing

We alway welcome your contributions 👏

  1. Fork the repository
  2. Create Feat_xxx branch
  3. Commit your code
  4. Create Pull Request

CHANGELOG

See Releases

License

MIT © sraph.com

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterCodec

func RegisterCodec(codec Codec)

RegisterCodec registers the provided Codec for use with all Transport clients and servers.

Types

type Codec

type Codec interface {
	// Marshal returns the wire format of v.
	Marshal(v interface{}) ([]byte, error)
	// Unmarshal parses the wire format into v.
	Unmarshal(data []byte, v interface{}) error
	// Name returns the name of the Codec implementation. The returned string
	// will be used as part of content type in transmission.  The result must be
	// static; the result cannot change between calls.
	Name() string
}

Codec defines the interface Transport uses to encode and decode messages. Note that implementations of this interface must be thread safe; a Codec's methods can be called from concurrent goroutines.

func GetCodec

func GetCodec(contentSubtype string) Codec

GetCodec gets a registered Codec by content-subtype, or nil if no Codec is registered for the content-subtype.

The content-subtype is expected to be lowercase.

Directories

Path Synopsis
Package proto defines the protobuf codec.
Package proto defines the protobuf codec.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL