Skip to content
This repository has been archived by the owner on Apr 5, 2024. It is now read-only.

Latest commit

 

History

History
96 lines (73 loc) · 1.84 KB

README.md

File metadata and controls

96 lines (73 loc) · 1.84 KB

Codec

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



Installation

go get go.nandlabs.io/commons/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 "go.nandlabs.io/commons/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 "go.nandlabs.io/commons/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)
  }
}