GoWind 开源生态GoWind 开源生态
首页
框架
GoWind Admin
GoWind CMS
GoWind IM
GoWind UBA
GoWind IoT
GoWind Toolkit
GoWind Quant
GitHub
首页
框架
GoWind Admin
GoWind CMS
GoWind IM
GoWind UBA
GoWind IoT
GoWind Toolkit
GoWind Quant
GitHub
  • 介绍

    • GoWind 框架
    • 框架整体架构
  • go-wind 核心

    • go-wind 核心框架
    • App 生命周期管理
    • Context 传播
    • Transport 抽象
    • Log 门面接口
  • go-wind-plugins 插件

    • go-wind-plugins 插件总览
    • 插件配置系统
    • 插件注册机制(SPI)
    • 日志适配插件
    • 传输协议插件
    • 消息中间件插件
    • 编码解码插件
    • 安全与认证插件
    • 链路追踪插件
    • 缓存插件
    • 对象存储插件(OSS)
    • 限流插件
    • 指标监控插件
    • AI 插件
    • 工作流插件
    • 数据库与缓存插件
    • Bootstrap 集成与网关插件
    • 压缩与序列化插件
    • 模板渲染与验证插件
  • go-wind-bootstrap 启动器

    • go-wind-bootstrap 声明式启动器
    • Bootstrap 配置系统
    • Bootstrap SPI 机制
    • 声明式中间件编排
    • Bootstrap CLI 工具
    • Bootstrap 实战示例
  • 教程

    • 快速入门教程
    • 自定义插件开发教程
    • 多协议同时监听教程
    • 框架迁移指南

编码解码插件

go-wind-plugins 提供统一的编解码接口,用于序列化/反序列化 HTTP 请求体、gRPC 消息、Broker 消息等。

一、Codec 接口

type Codec interface {
    Marshal(v interface{}) ([]byte, error)
    Unmarshal(data []byte, v interface{}) error
    Name() string
}

二、内置编码

编码导入路径Content-Type
JSONplugins/encoding/jsonapplication/json
Protobufplugins/encoding/protobufapplication/protobuf
YAMLplugins/encoding/yamlapplication/yaml
XMLplugins/encoding/xmlapplication/xml
MessagePackplugins/encoding/msgpackapplication/msgpack
TOMLplugins/encoding/tomlapplication/toml
Gobplugins/encoding/gobapplication/gob

三、注册 Codec

import (
    _ "github.com/tx7do/go-wind-plugins/encoding/json"
    _ "github.com/tx7do/go-wind-plugins/encoding/protobuf"
)

// init() 自动注册到全局 Codec 注册表

四、使用方式

4.1 编解码

import "github.com/tx7do/go-wind/encoding"

// 获取 codec
jsonCodec := encoding.GetCodec("json")

// 编码
data, _ := jsonCodec.Marshal(user)

// 解码
var user User
jsonCodec.Unmarshal(data, &user)

4.2 HTTP 请求/响应

// Transport 层根据 Content-Type 自动选择 codec
// 客户端发送 application/json → 使用 JSON codec
// 客户端发送 application/protobuf → 使用 Protobuf codec

4.3 Broker 消息

msg := &broker.Message{
    Headers: map[string]string{
        "Content-Type": "application/json",
    },
    Body: jsonData,
}

五、自定义 Codec

package mycodec

import "github.com/tx7do/go-wind/encoding"

type Codec struct{}

func (c *Codec) Marshal(v interface{}) ([]byte, error) {
    // 自定义序列化逻辑
    return serialize(v)
}

func (c *Codec) Unmarshal(data []byte, v interface{}) error {
    // 自定义反序列化逻辑
    return deserialize(data, v)
}

func (c *Codec) Name() string { return "my-format" }

func init() {
    encoding.RegisterCodec("my-format", &Codec{})
}

相关文档

  • 插件配置系统
  • 插件注册机制
  • 消息中间件插件
Edit this page
Last Updated:: 6/21/26, 9:28 PM
Contributors: Bobo
Prev
消息中间件插件
Next
安全与认证插件