coder

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: MIT Imports: 2 Imported by: 0

README

Coder

The coder package implements three interfaces with debug logging:
  • Encoder encodes and writes values to an output stream.
  • Decoder reads and decodes values from an input stream.
  • Coder is a pair of Encoder and Decoder.

Getting Started

package main

import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/gromey/proto-rest/coder"
)

func main() {
	coderJSON := coder.NewCoder("application/json", json.Marshal, json.Unmarshal)

	var buf bytes.Buffer

	in := &struct {
		A string `json:"a"`
	}{A: "AAA"}

	if err := coderJSON.Encode(&buf, in); err != nil {
		panic(err)
	}

	fmt.Printf("encoded: %s\n", buf.String())
	// encoded: {"a":"AAA"}

	out := &struct {
		A string `json:"a"`
	}{}

	if err := coderJSON.Decode(&buf, out); err != nil {
		panic(err)
	}

	fmt.Printf("decoded: %+v\n", out)
	// decoded: &{A:AAA}
}

Documentation

Index

Constants

View Source
const ContentType = "Content-Type"

Variables

This section is empty.

Functions

This section is empty.

Types

type Coder

type Coder interface {
	ContentType() string
	Encoder
	Decoder
}

A Coder is a pair of Encoder and Decoder.

func NewCoder

func NewCoder(contentType string, marshal func(v any) ([]byte, error), unmarshal func(data []byte, v any) error) Coder

NewCoder returns a new Coder.

type Decoder

type Decoder interface {
	Decode(r io.Reader, v any) error
}

A Decoder reads and decodes values from an input stream.

func NewDecoder

func NewDecoder(unmarshal func(data []byte, v any) error) Decoder

NewDecoder returns a new Decoder that reads from r.

type Encoder

type Encoder interface {
	Encode(w io.Writer, v any) error
}

An Encoder encodes and writes values to an output stream.

func NewEncoder

func NewEncoder(marshal func(v any) ([]byte, error)) Encoder

NewEncoder returns a new Encoder that writes to w.

Jump to

Keyboard shortcuts

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