Sovereign 8s.is mirror of standardgalactic/encoding-1
  • Go 95.8%
  • Makefile 2.5%
  • Shell 1.7%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Michael Persson 4a810d6b31 update README
2019-11-12 14:29:37 +01:00
_example rename encoding to codec 2018-09-25 13:43:26 -05:00
json rename encoding to codec 2018-09-25 13:43:26 -05:00
toml rename encoding to codec 2018-09-25 13:43:26 -05:00
yaml rename encoding to codec 2018-09-25 13:43:26 -05:00
.gitignore fix bug not applying options for ToBytes 2018-04-10 10:24:16 -05:00
.travis.yml add coverall and travis 2018-04-10 09:22:16 -05:00
coverall.sh exclude examples from tests 2018-06-12 12:47:20 -05:00
encoding.go add registered 2018-09-25 15:17:13 -05:00
errors.go refactor json encoding 2018-09-24 10:36:15 -05:00
LICENSE Create LICENSE 2018-04-08 15:37:18 -05:00
Makefile exclude examples from tests 2018-06-12 12:47:20 -05:00
README.md update README 2019-11-12 14:29:37 +01:00

GoDoc codecov Build Status Go Report Card License Mentioned in Awesome Go

encoding

Package provides a generic interface to encoders and decoders

Example

package main
  
import (
        "flag"
        "fmt"
        "log"
        "strings"

        "github.com/mickep76/encoding"
        _ "github.com/mickep76/encoding/json"
        _ "github.com/mickep76/encoding/toml"
        _ "github.com/mickep76/encoding/yaml"
)

type Message struct {
        Name, Text string
}

type Messages struct {
        Messages []*Message
}

func main() {
        codec := flag.String("codec", "json", fmt.Sprintf("Codecs: [%s].", strings.Join(encoding.Codecs(), ", ")))
        indent := flag.String("indent", "", "Indent encoding (only supported by JSON codec)")
        flag.Parse()

        in := Messages{
                Messages: []*Message{
                        &Message{Name: "Ed", Text: "Knock knock."},
                        &Message{Name: "Sam", Text: "Who's there?"},
                        &Message{Name: "Ed", Text: "Go fmt."},
                        &Message{Name: "Sam", Text: "Go fmt who?"},
                        &Message{Name: "Ed", Text: "Go fmt yourself!"},
                },
        }

        var opts []encoding.Option
        if *indent != "" {
                opts = append(opts, encoding.WithIndent(*indent))
        }
        c, err := encoding.NewCodec(*codec, opts...)
        if err != nil {
                log.Fatal(err)
        }

        b, err := c.Encode(in)
        if err != nil {
                log.Fatal(err)
        }

        fmt.Printf("Codec: %s\n", *codec)
        fmt.Printf("Encoded:\n%s\n", string(b))

        out := Messages{}
        if err := c.Decode(b, &out); err != nil {
                log.Fatal(err)
        }

        fmt.Println("Decoded:")
        for _, m := range out.Messages {
                fmt.Printf("%s: %s\n", m.Name, m.Text)
        }
}