codec

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

Codec Package

codec is a Go package that provides a flexible and type-safe framework for encoding and decoding data structures. It is designed to serialize complex Go types into a string representation, making them suitable for transport over the network or for storage in systems that require a string format (e.g., session data in cookies or metadata).

Core Features

  • Multiple Encoding Formats: Supports both GOB (Go's native binary encoding) and MessagePack (a fast, compact binary format) out of the box.
  • Type-Safe Generics: Uses Go generics to ensure that the type of data you encode is the same type you get back when you decode, preventing runtime type assertion errors.
  • Global Configuration: Allows you to set a default encoding method for the entire application once during initialization.
  • Base64 Encoding: Automatically encodes the binary output of GOB or MessagePack into a URL-safe Base64 string, making it easy to use in text-based protocols like HTTP headers or JSON fields.
  • gRPC Error Integration: Provides a ToStatus function to convert codec errors into detailed gRPC status errors, improving client-side error handling.

How to Use

1. Set the Default Codec (Optional)

In your application's main or init function, you can set the desired encoding method. This step is optional; if you don't set it, the default is GOB.

This can only be done once.

package main

import "github.com/94peter/vulpes/codec"

func main() {
    // Set MessagePack as the default codec for the application.
    // This must be done before any encoding or decoding operations.
    codec.WithCodecMethod(codec.MSGPACK)

    // ... rest of your application logic
}
2. Encode and Decode Data

Use the Encode and Decode functions to serialize and deserialize your data.

package main

import (
	"fmt"
	"log"

	"github.com/94peter/vulpes/codec"
)

// Define the data structure you want to work with.
type SessionData struct {
	UserID   string
	Username string
	Roles    []string
}

func main() {
	// Set the desired codec (optional, defaults to GOB).
	codec.WithCodecMethod(codec.MSGPACK)

	// 1. Create an instance of your data structure.
	mySession := SessionData{
		UserID:   "user-12345",
		Username: "alice",
		Roles:    []string{"admin", "editor"},
	}

	// 2. Encode the data into a string.
	encodedString, err := codec.Encode(mySession)
	if err != nil {
		log.Fatalf("Failed to encode session: %v", err)
	}

	fmt.Printf("Encoded Session: %s\n", encodedString)
	// This string is now safe to be stored in a cookie, a database, or sent in an HTTP header.

	// 3. Decode the string back into the original data structure.
	// You must specify the target type using generics.
	decodedSession, err := codec.Decode[SessionData](encodedString)
	if err != nil {
		log.Fatalf("Failed to decode session: %v", err)
	}

	fmt.Printf("Decoded UserID: %s\n", decodedSession.UserID)
	fmt.Printf("Decoded Username: %s\n", decodedSession.Username)

	// Verify that the decoded data matches the original.
	if mySession.UserID != decodedSession.UserID {
		log.Fatal("Data mismatch after decoding!")
	}
}

API Reference

  • WithCodecMethod(method CodecMethod): Sets the global default encoding method (codec.GOB or codec.MSGPACK). Can only be called once.
  • Encode(v any) (string, error): Encodes any Go type into a Base64 string using the default codec.
  • Decode[T any](s string) (T, error): Decodes a Base64 string back into a specific Go type T.
  • ToStatus(err wrapperErr.ErrorWithMessage) *status.Status: Converts a package-specific error into a gRPC status, useful for API error responses.

Documentation

Overview

Package codec provides a flexible framework for encoding and decoding data structures. It supports multiple encoding formats (GOB, MessagePack) and uses generics for type safety. The primary use case is to serialize complex types into a string format for transport or storage, for example, in session data.

Package codec provides a flexible framework for encoding and decoding data structures. It supports multiple encoding formats (GOB, MessagePack) and uses generics for type safety.

Package codec provides a flexible framework for encoding and decoding data structures. It supports multiple encoding formats (GOB, MessagePack) and uses generics for type safety.

Package codec provides a flexible framework for encoding and decoding data structures. It supports multiple encoding formats (GOB, MessagePack) and uses generics for type safety.

Package codec provides a flexible framework for encoding and decoding data structures. It supports multiple encoding formats (GOB, MessagePack) and uses generics for type safety.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ERR_UnknownCodecMethod is returned when an unsupported codec method is specified.
	ErrUnknownCodecMethod = errors.New("unknown codec method")
	// ERR_GobEncodeFailed is returned when GOB serialization fails.
	ErrGobEncodeFailed = errors.New("gob encode failed")
	// ERR_GobDecodeFailed is returned when GOB deserialization fails.
	ErrGobDecodeFailed = errors.New("gob decode failed")
	// ERR_MsgPackEncodeFailed is returned when MessagePack serialization fails.
	ErrMsgPackEncodeFailed = errors.New("msgpack encode failed")
	// ERR_MsgPackDecodeFailed is returned when MessagePack deserialization fails.
	ErrMsgPackDecodeFailed = errors.New("msgpack decode failed")
	// ERR_Base64DecodeFailed is returned when Base64 decoding of the input string fails.
	ErrBase64DecodeFailed = errors.New("base64 decode failed")

	// Status_CodecError is a pre-defined gRPC status for codec-related errors.
	Status_CodecError = status.New(codes.Internal, "codec error")
)

Standardized errors for the codec package.

Functions

func Decode

func Decode[T any](s string) (T, error)

Decode deserializes a string back into a specific type T using the globally configured default codec. The string is expected to be a Base64 representation of the binary data (GOB or MessagePack).

func Encode

func Encode(v any) (string, error)

Encode serializes a value of any type into a string using the globally configured default codec. The value is first encoded into a binary format (GOB or MessagePack) and then into a Base64 string.

func ToStatus

func ToStatus(err error) *status.Status

ToStatus converts a codec-related wrapper error into a gRPC status.Status. This is useful for providing detailed, structured error information to gRPC clients.

err: The wrapped error containing the original error and a descriptive message. Returns a gRPC status with detailed violation information, or nil if the input error is nil.

func WithCodecMethod

func WithCodecMethod(method CodecMethod)

WithCodecMethod sets the global default encoding method for the package. This function uses sync.Once to ensure that the codec method can only be set once, preventing inconsistent encoding/decoding formats during runtime. It should be called during the application's initialization phase.

Example:

func main() {
    codec.WithCodecMethod(codec.MSGPACK)
    // ... rest of the application
}

Types

type Codec

type Codec[T any] interface {
	// Encode serializes a given value of type T into a string.
	Encode(v T) (string, error)
	// Decode deserializes a string back into a value of type T.
	Decode(s string) (T, error)
	// Method returns the specific encoding method used by the codec.
	Method() CodecMethod
}

Codec defines the interface for any encoding/decoding implementation. It uses generics to ensure type safety between encoding and decoding operations.

type CodecMethod

type CodecMethod string

CodecMethod is a type that defines the available encoding formats. Using a custom type provides better type safety than using plain strings.

const (
	GOB     CodecMethod = "gob"     // GOB is a Go-specific binary encoding format.
	MSGPACK CodecMethod = "msgpack" // MessagePack is a fast, compact binary serialization format.
)

Constants for the supported encoding methods.

Jump to

Keyboard shortcuts

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