encoding

package
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package encoding 提供编解码器(Codec)的全局注册表, 用于按名称(如 "json"、"proto")或 HTTP Content-Type 选择对应的序列化实现。

各编解码器实现通常在自身包的 init() 中调用 Register 完成注册, 调用方通过 Get / GetWithCT 获取对应 Codec。

Index

Constants

This section is empty.

Variables

View Source
var Name = "encoding"

Functions

func Each

func Each(fn func(name string, cdc Codec))

Each 遍历所有已注册的编解码器。

func Keys

func Keys() []string

Keys 返回所有已注册编解码器的名称。

func Register

func Register(name string, cdc Codec)

Register 注册一个编解码器。name 与 cdc 均不可为空,且 name 不可重复注册, 否则会触发 panic(通过 recovery.Exit 统一处理)。

Types

type Codec

type Codec interface {
	// Name 返回编解码器名称,如 "json"、"proto"。
	Name() string
	// Encode 将对象序列化为字节切片。
	Encode(v any) ([]byte, error)
	// Decode 将字节切片反序列化到 v 指向的对象。
	Decode(data []byte, v any) error
	// Marshal 将对象序列化为字节切片。
	Marshal(v any) ([]byte, error)
	// Unmarshal 将字节切片反序列化到 v 指向的对象。
	Unmarshal(data []byte, v any) error
}

Codec 定义了一个编解码器需要实现的接口。 Encode/Decode 与 Marshal/Unmarshal 在多数实现中语义一致, 同时保留两组方法以兼容不同调用约定。

func Get

func Get(name string) Codec

Get 按名称返回已注册的编解码器,不存在时返回 nil。

func GetWithCT

func GetWithCT(ct string) Codec

GetWithCT 按 HTTP Content-Type 返回对应的编解码器,无匹配时返回 nil。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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