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

codec

package
v0.8.8 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 8 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 FormCodec added in v0.5.0

type FormCodec struct{}

FormCodec 是 application/x-www-form-urlencoded 编解码器(#7)。

边界(明示):仅支持**扁平**结构体字段(string/数值/bool/slice-of-scalar), 键名取 `form:"..."` tag(缺省用字段名);嵌套结构与 map 不支持—— form 语义本身是平铺 kv,需要嵌套请改用 json codec。 slice 编码为重复键(k=v1&k=v2),解码同样接受逗号分隔。

func (FormCodec) ContentType added in v0.5.0

func (FormCodec) ContentType() string

func (FormCodec) Marshal added in v0.5.0

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

func (FormCodec) Name added in v0.5.0

func (FormCodec) Name() string

func (FormCodec) Unmarshal added in v0.5.0

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

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