codec

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2025 License: MIT Imports: 12 Imported by: 1

README

Codec

Codec provides a unified interface for interacting with multiple formats along with validation



Installation

go get oss.nandlabs.io/golly/codec

Usage

It comes with a simple usage as explained below, just import the package, and you are good to go.

Codec Usage

Supported Formats
Format Status
JSON Completed
YAML Completed
XML Completed

Examples

Advanced Example
  1. JSON Codec - Encode struct
package main

import (
  "bytes"
  "fmt"
  codec "oss.nandlabs.io/golly/codec"
)

type Message struct {
  Name string `json:"name"`
  Body string `json:"body"`
  Time int64  `json:"time"`
}

func main() {
  m := Message{"TestUser", "Hello", 123124124}
  
  cd, _ := codec.Get("application/json", nil)
  buf := new(bytes.Buffer)
  if err := cd.Write(m, buf); err != nil {
    fmt.Errorf("error in write: %d", err)
  }
  // use buf in the application
}
Validation Example
package main

import(
  "bytes"
  "fmt"
  codec "oss.nandlabs.io/golly/codec"
)

//Message - add validations for the fields, codec internally validates the struct
type Message struct {
  Name string `json:"name" constraints:"min-length=5"`
  Body string `json:"body" constraints:"max-length=50"`
  Time int64  `json:"time" constraints:"min=10"`
}

func main() {
  m := Message{"TestUser", "Hello", 123124124}
  c, _ := codec.Get("application/json", nil)
  buf := new(bytes.Buffer)
  if err := c.Write(m, buf); err != nil {
    fmt.Errorf("error in write: %d", err)
  }
}

Documentation

Overview

Package codec provides a set of utilities for encoding and decoding data in Go.

Index

Constants

View Source
const (
	ValidateOnRead   = "ValidateOnRead"
	ValidateBefWrite = "ValidateBefWrite"
	Charset          = "charset"
	JsonEscapeHTML   = "JsonEscapeHTML"
	PrettyPrint      = "PrettyPrint"
)

Variables

This section is empty.

Functions

func Register added in v1.1.2

func Register(contentType string, readerWriter ReaderWriter)

Types

type BaseCodec

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

BaseCodec is a struct that encapsulates a ReaderWriter interface, a set of options, and a sync.Once instance to ensure that certain operations are only performed once. It is designed to handle encoding and decoding operations with customizable options.

func (*BaseCodec) DecodeBytes

func (bc *BaseCodec) DecodeBytes(b []byte, v interface{}) error

func (*BaseCodec) DecodeString

func (bc *BaseCodec) DecodeString(s string, v interface{}) error

func (*BaseCodec) EncodeToBytes

func (bc *BaseCodec) EncodeToBytes(v interface{}) ([]byte, error)

EncodeToBytes :

func (*BaseCodec) EncodeToString

func (bc *BaseCodec) EncodeToString(v interface{}) (string, error)

func (*BaseCodec) MimeTypes added in v1.1.2

func (bc *BaseCodec) MimeTypes() []string

MimeTypes

func (*BaseCodec) Read

func (bc *BaseCodec) Read(r io.Reader, v interface{}) (err error)

func (*BaseCodec) SetOption

func (bc *BaseCodec) SetOption(key string, value interface{})

SetOption sets an option for the BaseCodec instance. It initializes the options map if it hasn't been initialized yet. This method is thread-safe and can be called concurrently.

Parameters:

  • key: The option key as a string.
  • value: The option value as an interface{}.

func (*BaseCodec) Write

func (bc *BaseCodec) Write(v interface{}, w io.Writer) (err error)

type BaseConstraints

type BaseConstraints struct {
	// Name of the field
	Name string
	// Dimension holds the field dimension
	Dimension int
	// Required flag indicating if the field is a required field.
	Required bool
	// TargetNames stores map for known format types. This allows
	TargetNames map[string]string
	// TargetConfig stores configuration that is required by the target format . for Eg. Attribute config for XML etc.
	TargetConfig map[string]string
	// Sequence specifies the order  of the fields in the source/target format
	Sequence int
	//SkipField indicates that if the value of the field is absent/nil then skip the field while writing to data
	//This is similar to omitempty
	SkipField bool
}

BaseConstraints struct captures the basic information for a field

type BoolConstraints

type BoolConstraints struct {
	BaseConstraints
	DefaultVal *bool
}

BoolConstraints Struct

type BytesDecoder

type BytesDecoder interface {
	//DecodeBytes will decode a type from an array of bytes
	DecodeBytes(b []byte, v interface{}) error
}

BytesDecoder Interface

type BytesEncoder

type BytesEncoder interface {
	// EncodeToBytes will encode the provided type to []byte
	EncodeToBytes(v interface{}) ([]byte, error)
}

BytesEncoder Interface

type Codec

type Codec interface {
	Decoder
	Encoder
	ReaderWriter
	//SetOption sets an option to the reader and writer
	SetOption(key string, value interface{})
}

Codec Interface

func Get

func Get(contentType string, options map[string]interface{}) (c Codec, err error)

Get returns a Codec based on the provided content type and options. It supports JSON, XML, and YAML content types. If the content type contains a charset, it is added to the options but not used by the known JSON, XML, and YAML Read Writers.

Parameters:

  • contentType: A string representing the MIME type of the content.
  • options: A map of options to configure the Codec.

Returns:

  • c: A Codec configured for the specified content type.
  • err: An error if the content type is unsupported.

func GetDefault

func GetDefault(contentType string) (Codec, error)

GetDefault function creates an instance of codec based on the contentType and defaultOptions

func JsonCodec added in v1.1.2

func JsonCodec() Codec

JsonCodec Provides a JSONCodec JsonCodec returns a Codec for handling JSON data. It retrieves the default Codec for the MIME type "application/json". If there is an error during retrieval, it is ignored and the default Codec is returned.

func XmlCodec added in v1.1.2

func XmlCodec() Codec

XmlCodec returns a Codec for handling XML data. It retrieves the default Codec associated with the MIME type for XML text. The function ignores any error that might occur during the retrieval process.

func YamlCodec added in v1.1.2

func YamlCodec() Codec

YamlCodec Provides a YamlCodec

type Decoder

type Decoder interface {
	StringDecoder
	BytesDecoder
}

Decoder Interface

type Encoder

type Encoder interface {
	StringEncoder
	BytesEncoder
}

Encoder Interface

type F32Constraints

type F32Constraints struct {
	BaseConstraints
	DefaultVal *float32
	Min        *float32 //The value is inclusive
	Max        *float32 //The value is inclusive
}

F32Constraints Struct

type F64Constraints

type F64Constraints struct {
	BaseConstraints
	DefaultVal *float64
	Min        *float64 //The value is inclusive
	Max        *float64 //The value is inclusive
}

F64Constraints Struct

type IntConstraints

type IntConstraints struct {
	BaseConstraints
	DefaultVal *int
	Min        *int //The value is inclusive
	Max        *int //The value is inclusive
}

IntConstraints Struct

type ReaderWriter

type ReaderWriter interface {
	//Write a type to writer
	Write(v interface{}, w io.Writer) error
	//Read a type from a reader
	Read(r io.Reader, v interface{}) error
	//MimeTypes returns a slice of strings representing the MIME types
	MimeTypes() []string
}

ReaderWriter is an interface that defines methods for writing and reading data to and from an io.Writer and io.Reader, respectively.

Write writes the given value to the provided writer. It takes an interface{} value and an io.Writer, and returns an error if the write operation fails.

Read reads data from the provided reader into the given value. It takes an io.Reader and an interface{} value, and returns an error if the read operation fails.

type StrConstraints

type StrConstraints struct {
	BaseConstraints
	DefaultVal *string
	Pattern    *string
	Format     *string
	MinLength  *int
	MaxLength  *int
}

StrConstraints Struct

type StringDecoder

type StringDecoder interface {
	//DecodeString will decode  a type from string
	DecodeString(s string, v interface{}) error
}

StringDecoder Interface

type StringEncoder

type StringEncoder interface {
	//EncodeToString will encode a type to string
	EncodeToString(v interface{}) (string, error)
}

StringEncoder Interface

type StructMeta

type StructMeta struct {
	Fields map[string]string
}

StructMeta Struct

type UIntConstraints

type UIntConstraints struct {
	BaseConstraints
	DefaultVal *uint
	Min        *uint //The value is inclusive
	Max        *uint //The value is inclusive
}

UIntConstraints Struct

type Validator

type Validator interface {
	Validate() (bool, []error)
}

Validator is an interface that defines a method for validating an object. The Validate method returns a boolean indicating whether the validation was successful, and a slice of errors detailing any validation issues.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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