Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Initial support of custom tag handler for v3 for scalar values #935

Open
wants to merge 6 commits into
base: v3
Choose a base branch
from

Conversation

lelvisl
Copy link

@lelvisl lelvisl commented Jan 30, 2023

Hi!

In this PR I want add initial support of custom tag handlers for scalar values

example code

package main

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"strings"
)

var data = `
a: !envstring SECRET
b: 
  c: 85
  d: [3, 4]
`

func main() {
	os.Setenv("SECRET", "pass")
	fmt.Println("hi")
	var foo struct {
		A string
		B interface{}
	}
	dec := yaml.NewDecoder(strings.NewReader(data))
	dec.SetTagHandler("!envstring", EnvTagHandler{}.Handle)
	err := dec.Decode(&foo)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(foo)
	fmt.Println(foo.A)
}

type EnvTagHandler struct{}

func (e EnvTagHandler) Handle(str string) (any, error) {
	return os.Getenv(str), nil
}

In future all default tags can be implemented as tag handlers.

@lelvisl
Copy link
Author

lelvisl commented Jan 30, 2023

@niemeyer please look at this PR. If you basically agree, i will add tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants