typedconf

package
v0.0.0-...-4c3641f Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2021 License: GPL-3.0 Imports: 3 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Decoders

type Decoders interface {
	Register(key string, create func() interface{})
	Instance() Instance
}

func NewJSONDecoders

func NewJSONDecoders() Decoders
Example (Slice)
package main

import (
	"github.com/GodsBoss/go-pkg/typedconf"

	"encoding/json"
	"fmt"
	"strings"
)

func main() {
	input := []byte(
		`
			{
				"sources": [
					{
						"type": "inline",
						"content": "Hello, world!"
					},
					{
						"type": "replace",
            "pattern": "$a $b $c",
            "replace": {
              "$a": "foo",
              "$b": "bar",
              "$c": "baz"
            }
					}
				]
			}
		`,
	)
	cfg := &Config{}
	err := json.Unmarshal(input, cfg)
	if err != nil {
		fmt.Printf("Error: %+v\n", err)
		return
	}
	for _, source := range cfg.Sources {
		txt, _ := source.Text()
		fmt.Println(txt)
	}

}

type Config struct {
	Sources TextSources `json:"sources"`
}

type TextSources []TextSource

func (sources *TextSources) UnmarshalJSON(data []byte) error {
	decoders := typedconf.NewJSONDecoders()
	decoders.Register("inline", func() interface{} {
		return &InlineSource{}
	})
	decoders.Register("replace", func() interface{} {
		return &ReplacerSource{}
	})
	list := []struct{}{}
	err := json.Unmarshal(data, &list)
	if err != nil {
		return err
	}
	decoded := make([]typedconf.Instance, len(list))
	for index := range list {
		decoded[index] = decoders.Instance()
	}
	err = json.Unmarshal(data, &decoded)
	if err != nil {
		return err
	}
	*sources = make(TextSources, len(list))
	for index, dec := range decoded {
		(*sources)[index] = dec.Value().(TextSource)
	}
	return nil
}

type TextSource interface {
	Text() (string, error)
}

type InlineSource struct {
	Content string `json:"content"`
}

func (source *InlineSource) Text() (string, error) {
	return source.Content, nil
}

type ReplacerSource struct {
	Pattern      string            `json:"pattern"`
	Replacements map[string]string `json:"replace"`
}

func (source ReplacerSource) Text() (string, error) {
	content := source.Pattern
	for o, n := range source.Replacements {
		content = strings.Replace(content, o, n, -1)
	}
	return content, nil
}
Output:

Hello, world!
foo bar baz

func NewXMLDecoders

func NewXMLDecoders() Decoders
Example (Instance)
package main

import (
	"github.com/GodsBoss/go-pkg/typedconf"

	"encoding/xml"
	"fmt"
)

func main() {
	input := []byte(
		`
      <list>
        <item>
          <op type="-">
            <value>-5000</value>
          </op>
        </item>
        <item>
          <op type="+">
            <value>-50</value>
            <value>80</value>
            <value>-5</value>
          </op>
        </item>
      </list>
    `,
	)
	list := &List{}
	err := xml.Unmarshal(input, list)
	if err != nil {
		fmt.Printf("Error: %+v\n", err)
	}

	for _, item := range list.Items {
		fmt.Printf("%d\n", item.Op.Calc())
	}

}

type List struct {
	XMLName xml.Name
	Items   []Item `xml:"item"`
}

type Item struct {
	Op Operation
}

func (it *Item) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	decoder := typedconf.NewXMLDecoders()
	decoder.Register("-", func() interface{} {
		return &Negate{}
	})
	decoder.Register("+", func() interface{} {
		return &Add{}
	})
	inst := decoder.Instance()
	i := &item{
		Inst: inst,
	}
	err := d.Decode(inst)
	if err != nil {
		return err
	}
	it.Op = i.Inst.Value().(Operation)
	d.Skip()
	return nil
}

type item struct {
	Inst typedconf.Instance `xml:"op"`
}

type Operation interface {
	Calc() int
}

type Negate struct {
	Value int `xml:"value"`
}

func (neg Negate) Calc() int {
	return -neg.Value
}

type Add struct {
	Values []int `xml:"value"`
}

func (add Add) Calc() int {
	result := 0
	for _, value := range add.Values {
		result += value
	}
	return result
}
Output:

5000
25

type Instance

type Instance interface {
	// Value returns the concrete value created by unmarshaling.
	Value() interface{}
}

Instance is an instance which can be unmarshaled and stores the resulting unmarshaled concrete type.

Jump to

Keyboard shortcuts

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