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

codec

package
v1.73.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 3 Imported by: 0

README

Package codec

Пакет codec предоставляет реализации для кодирования и декодирования payload.

Поддерживаются:

  • потоковое кодирование (io.Writer / io.Reader)
  • кодирование/декодирование в память ([]byte)
  • переиспользуемые реализации через pooling (для снижения аллокаций)

Types

Zstd

Реализация кодека на базе Zstandard.

NewZstd(cfg ZstdConfig) *Zstd

Создаёт новый экземпляр Zstd-кодека.

ZstdConfig:

  • Level — уровень сжатия (zstd.EncoderLevel)
(z *Zstd) EncodingType() string

Возвращает тип кодирования:

"zstd"

Encoding

(z *Zstd) Encode(w io.Writer) (io.WriteCloser, error)

Создаёт потоковый энкодер.

Используется для записи данных в поток с последующим сжатием.

Пример:

enc, err := codec.Encode(w)
if err != nil {
	return err
}
defer enc.Close()

_, _ = enc.Write(data)
(z *Zstd) EncodeBytes(data []byte) ([]byte, error)

Кодирует байтовый срез в память.

Используется для случаев, когда не нужен streaming API.

Decoding

(z *Zstd) Decode(body io.ReadCloser) (io.ReadCloser, error)

Оборачивает входной поток декодером.

Возвращаемый ReadCloser автоматически декодирует данные при чтении.

(z *Zstd) DecodeBytes(data []byte) ([]byte, error)

Декодирует данные из памяти.

Internals

Пакет использует pooling энкодеров (sync.Pool) для снижения нагрузки на GC.

Основные оптимизации:

  • повторное использование zstd.Encoder
  • минимизация аллокаций при streaming encode
  • разделение streaming и byte API

Usage

HTTP / middleware example
codec := codec.Default

encoded, err := codec.EncodeBytes(data)
if err != nil {
	return err
}
Decode example
codec := codec.Default

decoded, err := codec.DecodeBytes(encoded)
if err != nil {
	return err
}

Documentation

Overview

Package codec provides abstractions and implementations for payload encoding and decoding.

The package defines common interfaces for streaming and byte-based codecs that can be used by transports such as HTTP, gRPC, and AMQP. It also provides a reusable Zstandard (zstd) implementation with encoder pooling for efficient compression.

Codecs support both streaming APIs (io.Reader/io.Writer) and in-memory byte slice operations, allowing the same implementation to be reused across different transports and middleware.

Example usage:

codec := codec.Default

// Encode bytes.
encoded, err := codec.EncodeBytes(data)
if err != nil {
	log.Fatal(err)
}

// Decode bytes.
plain, err := codec.DecodeBytes(encoded)
if err != nil {
	log.Fatal(err)
}

Index

Constants

View Source
const (
	ZstdSpeedFastest           = zstd.SpeedFastest
	ZstdSpeedDefault           = zstd.SpeedDefault
	ZstdSpeedBetterCompression = zstd.SpeedBetterCompression
	ZstdSpeedBestCompression   = zstd.SpeedBestCompression
)
View Source
const DefaultEncodeThreshold = 128 * 1024

Variables

This section is empty.

Functions

This section is empty.

Types

type Codec

type Codec interface {
	Type() string

	EncodeBytes(b []byte) ([]byte, error)
	DecodeBytes(b []byte) ([]byte, error)

	Encode(w io.Writer) (io.WriteCloser, error)
	Decode(rc io.ReadCloser) (io.ReadCloser, error)
}
var (
	Default Codec = NewZstd(ZstdConfig{
		Level: ZstdLevel(ZstdSpeedDefault),
	})
)

type Zstd

type Zstd struct {
	// contains filtered or unexported fields
}

func NewZstd

func NewZstd(cfg ZstdConfig) *Zstd

NewZstd create instance of zstd

func (*Zstd) Decode

func (m *Zstd) Decode(body io.ReadCloser) (io.ReadCloser, error)

Decode wraps body with a zstd decoder.

func (*Zstd) DecodeBytes

func (m *Zstd) DecodeBytes(data []byte) ([]byte, error)

DecodeBytes decodes bytes body using zstd.

func (*Zstd) Encode

func (m *Zstd) Encode(w io.Writer) (io.WriteCloser, error)

Encode data using zstd.

func (*Zstd) EncodeBytes

func (m *Zstd) EncodeBytes(data []byte) ([]byte, error)

EncodeBytes encode data using zstd.

func (*Zstd) Type

func (*Zstd) Type() string

type ZstdConfig

type ZstdConfig struct {
	Level ZstdLevel
}

type ZstdLevel

type ZstdLevel zstd.EncoderLevel

Level is an alias for zstd.EncoderLevel representing encoder compression levels.

Jump to

Keyboard shortcuts

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