Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,12 @@ func (e *Encoder) encodeValue(ctx context.Context, v reflect.Value, column int)
if e.isInvalidValue(v) {
return e.encodeNil(), nil
}
if v.CanInterface() {
iface := v.Interface()
if node, ok := iface.(ast.Node); ok {
return node, nil
}
}
if e.canEncodeByMarshaler(v) {
node, err := e.encodeByMarshaler(ctx, v, column)
if err != nil {
Expand Down
21 changes: 21 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/goccy/go-yaml"
"github.com/goccy/go-yaml/ast"
"github.com/goccy/go-yaml/parser"
"github.com/goccy/go-yaml/token"
)

var zero = 0
Expand Down Expand Up @@ -2146,3 +2147,23 @@ a: &anc !mytag
func ptr[T any](v T) *T {
return &v
}

type customNodeMarshaler struct {
Node ast.Node
}

func (c *customNodeMarshaler) MarshalYAML() (interface{}, error) {
return c.Node, nil
}

func TestCustomNodeMarshaler(t *testing.T) {
n := ast.String(token.String("custom", "", &token.Position{}))
b, err := yaml.Marshal(&customNodeMarshaler{Node: n})
if err != nil {
t.Fatal(err)
}
expected := "custom\n"
if string(b) != expected {
t.Fatalf("failed to encode. expected %s but got %s", expected, string(b))
}
}