Help us shape the future of Go! Take the 2026 Go Developer Survey

codec

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package codec 提供请求/响应编解码器的注册制抽象(参照 go-kratos encoding)。

Client.DoCodec 按 codecName 序列化请求体、设置对应 Content-Type, 响应按 Content-Type 反查 codec 反序列化(查不到回退请求 codec)。 json 内置注册;form/protobuf 等按需 RegisterCodec 扩展。

实现必须并发安全:Codec 的方法会被并发调用。

Index

Constants

View Source
const DefaultName = "json"

DefaultName 是默认编解码器名称(json,包 init 时注册)。

Variables

This section is empty.

Functions

func RegisterCodec

func RegisterCodec(c Codec)

RegisterCodec 注册编解码器(按 Name() 小写归一)。nil 或空名 panic; 同名重复注册覆盖(测试与扩展场景)。

Types

type Codec

type Codec interface {
	// Name 返回编解码器名称(注册键;调用方注册时会转小写)。
	// 返回值必须静态不变。
	Name() string
	// ContentType 返回对应的 HTTP Content-Type(如 application/json)。
	ContentType() string
	// Marshal 序列化 v 为线上格式。
	Marshal(v any) ([]byte, error)
	// Unmarshal 解析线上格式到 v。
	Unmarshal(data []byte, v any) error
}

Codec 是传输编解码接口。

func GetCodec

func GetCodec(name string) Codec

GetCodec 按名称(大小写不敏感)取已注册编解码器,未注册返回 nil。

func MustGetCodec

func MustGetCodec(name string) Codec

MustGetCodec 按名称取编解码器,未注册 panic。

type JSONCodec

type JSONCodec struct{}

JSONCodec 是内置 JSON 编解码器(encoding/json),与 v0.3.x GetJSON 的序列化行为一致。

func (JSONCodec) ContentType

func (JSONCodec) ContentType() string

func (JSONCodec) Marshal

func (JSONCodec) Marshal(v any) ([]byte, error)

func (JSONCodec) Name

func (JSONCodec) Name() string

func (JSONCodec) Unmarshal

func (JSONCodec) Unmarshal(data []byte, v any) error

Jump to

Keyboard shortcuts

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