yamlc

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2022 License: BSD-3-Clause Imports: 4 Imported by: 0

README

yamlc (YAML channel)

GoDoc builds.sr.ht status

Wrapper for http://gopkg.in/yaml.v3 to allow one to preregister structs as unmarshal targets. This allows one to iterate through a channel to unmarshal any amount of YAML documents from an io.Reader.

This library can be used for things like reading files with multiple --- separated YAML documents where each one has different data structure without having to know the input beforehand.

Example

package main

import (
	"fmt"
	"log"
	"strings"
	"git.sr.ht/~errnoh/yamlc"
)

func init() {
	RegisterKind("type-a", StructA{})
	RegisterKind("type-b", StructB{})
}

type StructA struct {
	Kind string `yaml:"Kind"`
	A    string `yaml:"a"`
}

type StructB struct {
	Kind string `yaml:"Kind"`
	B    int    `yaml:"b"`
}

var data = `
Kind: type-a
a: foobar
---
Kind: type-b
b: 42
`

func main() {
	r := strings.NewReader(data)

	for v := range Decode(r) {
		switch val := v.(type) {
		case *StructA:
			fmt.Println(val.Kind, val.A)
		case *StructB:
			fmt.Println(val.Kind, val.B)
		case error:
			log.Fatal(val)
		}
	}
}

Output:

type-a foobar
type-b 42

Documentation

Overview

Wrapper for easy decoding of YAML multi-document inputs

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(r io.Reader) <-chan interface{}

Decode reads YAML from `io.Reader`, unmarshals each document into a registered struct and returns them through the channel.

Example (Embedded)
package main // import "git.sr.ht/~errnoh/yamlc"

import (
	"fmt"
	"log"
	"strings"
)

// Simple example showing everything that's needed
// for registering types and decoding YAML from io.Reader

func init() {
	RegisterKind("type-a", StructA{})
	RegisterKind("type-b", StructB{})
}

type StructA struct {
	Kind string `yaml:"Kind"`
	A    string `yaml:"a"`
}

type StructB struct {
	Kind string `yaml:"Kind"`
	B    int    `yaml:"b"`
}

var data = `
Kind: type-a
a: foobar
---
Kind: type-b
b: 42
`

func main() {
	r := strings.NewReader(data)

	for v := range Decode(r) {
		switch val := v.(type) {
		case *StructA:
			fmt.Println(val.Kind, val.A)
		case *StructB:
			fmt.Println(val.Kind, val.B)
		case error:
			log.Fatal(val)
		}
	}
}
Output:

type-a foobar
type-b 42

func RegisterKind

func RegisterKind(name string, v interface{})

RegisterKind registers a struct that should be used when encountering a yaml with Kind that matches 'name'.

func SetKindField

func SetKindField(name string)

SetKindField changes the field that's used for matching type to a struct. This defaults to `Kind`.

Types

This section is empty.

Jump to

Keyboard shortcuts

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