Documentation
¶
Overview ¶
Package encoding puts a JSON serializer behind an interface.
s := encoding.NewJSONSerializer()
data, err := s.Serialize(order)
if err != nil {
return err
}
var decoded Order
err = s.Deserialize(data, &decoded)
The value of the indirection is substitutability: code that takes a JSONSerializer can be handed a fake in tests, or a different encoding later, without changing its signature.
The implementation is github.com/goccy/go-json, which is a drop-in replacement for encoding/json - same struct tags, same semantics.
No other package in this repository consumes it yet: pkg/cache marshals with goccy directly and pkg/stream uses the standard library.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type JSONSerializer ¶
type JSONSerializer interface {
Serialize(v any) ([]byte, error)
Deserialize(data []byte, v any) error
}
JSONSerializer converts Go values to JSON and back. Deserialize takes a pointer to the destination, as encoding/json does.
func NewJSONSerializer ¶
func NewJSONSerializer() JSONSerializer
NewJSONSerializer returns a JSONSerializer backed by github.com/goccy/go-json, which honours the same struct tags as encoding/json.
Example ¶
package main
import (
"fmt"
"github.com/diegodesousas/go-devkit/pkg/encoding"
)
type product struct {
Name string `json:"name"`
Price int `json:"price"`
}
func main() {
s := encoding.NewJSONSerializer()
data, err := s.Serialize(product{Name: "keyboard", Price: 300})
if err != nil {
panic(err)
}
fmt.Println(string(data))
var decoded product
if err := s.Deserialize(data, &decoded); err != nil {
panic(err)
}
fmt.Println(decoded.Name, decoded.Price)
}
Output: {"name":"keyboard","price":300} keyboard 300