go-openapi go-yaml

A YAML 1.2 parser, decoder and encoder for Go, with a syntax tree that keeps positions, comments and the source text of every token.

Status

Experimental. There is no tagged release and the API still moves — see Status.

Getting started

go get github.com/go-openapi/go-yaml

Then read Which layer you need.

Licensing

SPDX-FileCopyrightText: Copyright 2025 go-swagger maintainers

This library ships under the Apache-2.0 license.

Contributing

Issues and pull requests welcome.

See the shared go-openapi contributing guidelines.


  • Install go-yaml, decode a document, encode one back.

    And decide which of the two APIs you need: the codec, or the parser and the AST.

  • Read, query and change a YAML document without turning it into Go values.

    Key order, comments, positions, non-string keys and numbers Go cannot hold — all of it survives, because nothing is projected onto a Go type.

  • The codec: turning YAML into Go values and back.

    Marshal and Unmarshal, the options that steer them, struct tags, anchors, comments and errors.

  • Why this library exists, how correct it is, how fast it is, and what is not built yet.
  • Repo-level information for github.com/go-openapi/go-yaml.

    Contributing guidelines and maintainer documentation are shared across the go-openapi organization.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Subsections of go-openapi go-yaml

Getting started

Install

go get github.com/go-openapi/go-yaml

Requires Go 1.26.0 or newer.

No release yet

The module has no tagged version. go get resolves a pseudo-version on master, and the API still moves. See Status.

Decode

TODO — the smallest useful Unmarshal into a struct, and the same into any.

Encode

TODO — Marshal of the same value, and what the default output looks like.

Then what

Read Which layer you need. Most callers stay in Usage; Advanced is for programs that work on the document rather than on Go values.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Subsections of Getting started

Which layer you need

Start here

Answer yes to any of these and you want the document layer:

  • the output has to keep the input’s key order, or its comments
  • you have to report a line and a column back to a user
  • you do not control the schema, so there is no struct to decode into
  • the document uses YAML that Go cannot hold — a sequence as a key, a number wider than int64, a subtree shared by an anchor
  • you only need one value out of a large document

Otherwise you want the codec: Marshal, Unmarshal, a struct, done.

What each layer costs you

documentsvalues
entry pointparser.ParseBytesyaml.Unmarshal
you geta tree of ast.Nodeyour Go type
key orderkeptlost through a map, fixed by a struct
commentskept, with parser.WithCommentsonly through a CommentMap
positionson every tokennone
non-string keyskept, with their kindstringified, or refused
numbers past int64kept as written*big.Int into any, an overflow error into a typed field
writing backthe renderer’s layout, not the source’swhatever the encoder produces
what you writemore codeless code

Neither layer is a wrapper over the other in the direction you might expect: the codec is built on the parser, so anything the codec does the document layer can do, and the reverse does not hold.

Mixing the two

You do not have to choose once.

  • codec.NodeToValue fills a Go value from a node you already have, so you can walk a document and decode only the parts you care about.
  • codec.ValueToNode goes the other way, turning a Go value into a subtree you can splice into a document.
  • expressions.Path has both: Read and Filter hand you a Go value, ReadNode and FilterNode stop at the tree.
  • codec.ToJSON converts a whole document without building a Go value at all.

Streaming

Not built. A parse reads the whole document before it returns. parser.WithOnComplete is the seam a streaming API will use and is marked an experiment; it does not bound what the parse holds. See Status.

The packages, in dependency order

token → ast → errors → parser → codec → expressions

No package imports one to its right. The root package (github.com/go-openapi/go-yaml) re-exports Marshal, Unmarshal, ToJSON and FromJSON — the four calls that take no option. Everything with options is in codec.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Migrating

Outline

This page is an outline. The structure is settled; the prose is not written.

What the page must answer

  • Can I swap the import path and compile?
  • Which of my documents decode to something different, and why?

Sections

From go.yaml.in/yaml/v3

Marshal and Unmarshal match. The struct-tag default is v3’s, held by a parity table in the test suite — see Struct tags. What differs: no yaml.Node; the tree is ast and the entry point is parser.ParseBytes.

From goccy/go-yaml

This library is a hard fork of goccy/go-yaml. The packages are the same names. List what moved out of the root, and what the option names are now.

From gopkg.in/yaml.v2

Mostly the same story as v3, plus v2’s own tag quirks.

Open questions for the API

  • There is no yaml.Node equivalent with a stable, small surface. ast.Node is an interface over ~30 concrete types. A migrating caller has nothing to put in a struct field. Is that a gap, or the point of the fork?
Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Working with documents

Most YAML libraries offer one thing: fill a Go value from a document, or write a document from a Go value. That is the job the codec does, and for configuration read once into a struct it is the right job.

It is also lossy, and for a whole class of work the loss is the problem. Put the Go type system between you and the document and you lose what no Go type holds — the order the keys were written in, the comments, where each construct sits in the source — and you cannot represent what Go has no type for.

What the two layers see

Take this document:

# the service
name: pet-store      # a line comment
version: 1.2.3
limits:
  max: 18446744073709551615
? [a, b]
: a sequence used as a key

Unmarshal into map[string]any refuses it outright:

[6:1] cannot use []interface {} as a map key: it is not comparable
   3 | version: 1.2.3
   4 | limits:
   5 |   max: 18446744073709551615
>  6 | ? [a, b]
       ^
   7 | : a sequence used as a key

Into any it succeeds, and four things are gone:

map[string]any{
	"[a b]":   "a sequence used as a key",
	"limits":  map[string]any{"max": 0xffffffffffffffff},
	"name":    "pet-store",
	"version": "1.2.3",
}

The comments are gone. The key order is gone — a Go map has none. Every position is gone. And [a, b], a sequence, arrives as the string "[a b]", so nothing downstream can tell it from a key someone typed that way.

Parsed as a document, all four survive:

f, err := parser.ParseBytes(src, parser.WithComments())
if err != nil {
	// ...
}
for _, kv := range f.Docs[0].Body.(*ast.MappingNode).Values {
	tk := kv.Key.GetToken()
	comment := ""
	if c := kv.GetComment(); c != nil {
		comment = c.String()
	}
	fmt.Printf("%-10s line=%d col=%d kind=%v %s\n",
		kv.Key.String(), tk.Position.Line, tk.Position.Column, kv.Key.Type(), comment)
}
name       line=2 col=1 kind=String # the service
version    line=3 col=1 kind=String
limits     line=4 col=1 kind=String
? [a, b]   line=6 col=1 kind=MappingKey

The keys come back in the order the document wrote them, each with its position and its real kind. GetComment returns the comment above a key, so name carries # the service; the trailing # a line comment is a separate token on the value.

When you need this layer

  • You have to write the document back. Preserving key order through a Go map is impossible; through a struct it is possible only for a schema you control.
  • The document carries comments you must keep, or must read.
  • You are reporting on the source — a linter, a language server, an editor. A diagnostic needs a line and a column, and a Go value has neither.
  • The schema is not yours. An arbitrary document has no struct to decode into.
  • The document uses YAML that JSON and Go cannot express: a mapping or a sequence as a key, a number wider than int64, an anchor shared between two branches.
  • You only need part of it. Finding the position of one key does not require building a value for the whole document.

The packages

packageholds
parserParseBytes, ParseFile, and the options that decide what the tree keeps
astthe tree: node types, Walk, Filter, Merge, and the renderer
tokena token, its position, and its text as written
expressionsPath and PathString, to address a node by path
codecToJSON and FromJSON, which convert without building a Go value
  • Turning bytes into a tree, and the options that decide what the tree keeps.
  • Node types, walking a tree, finding a node, changing one, and writing the document back.
  • What a token holds, how it addresses the source it came from, and the functions that read a YAML scalar spelling on their own.
  • Addressing a node by path: reading it, replacing it, annotating the source around it, and building a path in code.
  • Converting a YAML document to JSON without building a Go value for it, and what it refuses.
Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Subsections of Working with documents

Parser

Parsing

f, err := parser.ParseBytes(src, parser.WithComments())
if err != nil {
	// ...
}
for _, doc := range f.Docs {
	// doc.Body is the root node of one document
}

ParseFile reads a path. parser.New builds a Parser you can hold and reuse with a fixed set of options.

An *ast.File holds every document in the stream, in Docs. A stream with one document has one entry; --- starts another.

The options

optionwhat it changes
WithCommentskeeps comments. They are dropped by default, before the grouping ever sees them.
WithYAMLVersionreads under 1.0, 1.1 or 1.2 rather than the document’s own directive
WithAnchorspublishes anchors declared in another parse
WithMergeKeysresolves a bare << as a merge key at any version, and changes nothing else
WithLaxTagsreads !!int abc as the text abc instead of refusing the document
WithAllowDuplicateMapKeyaccepts a repeated key instead of refusing it
WithJSONCompatiblereports 1: and "1": in one mapping as ErrNotJSON, since both write the JSON name "1"
WithOmitNodePathsstops recording each node’s path
WithChunkSizehow many tokens one chunk of the token arena holds
WithOnCompletecalls a function with each node as the parser finishes it
WithOmitNodePaths turns off more than it says

Node paths are what ast.Node.GetPath returns and what a CommentMap is keyed by. Omit them and GetPath returns "", and the map codec.CommentToMap fills comes back keyed by empty strings. Neither reports anything.

Paths are recorded by default and cost little. Reach for this only when you have measured that they cost you.

Anchors across a parse

The parser owns the anchor table. It resolves every alias against the anchors of the document holding it, and refuses one that names none — so a fragment meant to be read beside other files has to be handed their anchors:

f, err := parser.ParseBytes(fragment, parser.WithAnchors(anchors))

Pass ast.DocumentNode.Anchors from the parse that declared them. This is also what codec.ReferenceFiles needs when you drive the decode from a node you parsed yourself.

Reading a node as the parser finishes it

WithOnComplete reports each node in completion order — a node’s children before the node itself.

Note

This is the seam a streaming API will use, and it is marked an experiment in the source. It is not a streaming API: ParseBytes still reads the whole document before it returns. See Status.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

The syntax tree

Editing a document, end to end

Parse, find the node, replace it, write it out:

src := []byte("# service\nname: pet-store\nversion: 1.2.3   # bump me\nports:\n  - 80\n  - 443\n")

f, err := parser.ParseBytes(src, parser.WithComments())
if err != nil {
	// ...
}

p, err := expressions.PathString("$.version")
if err != nil {
	// ...
}
n, err := p.FilterNode(f.Docs[0].Body)   // "1.2.3 # bump me", String, at 3:10

newVal := ast.String(token.New("2.0.0", "2.0.0", n.GetToken().Position))
if err := p.ReplaceWithNode(f, newVal); err != nil {
	// ...
}

fmt.Print(f)
# service
name: pet-store
version: 2.0.0
ports:
- 80
- 443
The layout is the renderer’s, not the document’s

Compare that output with the input. Three things moved that you did not ask to move:

  • ports: had its entries indented two spaces; they come back at column 0
  • version: 1.2.3 # bump me had three spaces before the comment
  • # bump me is gone entirely — it belonged to the node that was replaced

Indentation comes from depth in the tree, not from the positions the document was read at: those positions say where a node was, which stops being true the moment anything is edited. So an edit-and-write-back changes the shape of the whole document, not just the line you touched.

If you need the rest of the file untouched, use the positions to splice the new text into the original bytes yourself. Rendering a document back byte for byte is a target, not a feature.

The node types

Every node satisfies ast.Node — String, GetToken, Type, GetComment, GetPath. Beyond that they group by shape:

familytypes
scalarsStringNode, IntegerNode, FloatNode, BoolNode, NullNode, InfinityNode, NanNode, LiteralNode
collectionsMappingNode, MappingValueNode, SequenceNode, SequenceEntryNode
keysMappingKeyNode (an explicit ? key), MergeKeyNode
referencesAnchorNode, AliasNode
structureDocumentNode, DirectiveNode, TagNode, CommentNode, CommentGroupNode

Four interfaces cut across them: ScalarNode, MapNode, MapKeyNode, ArrayNode. A MappingNode holds Values []*MappingValueNode, in document order, each with a Key and a Value.

Walking

ast.Walk(visitor, node)     // visitor.Visit(n) returns the visitor for the children
ast.Filter(typ, node)       // every node of one type, under node
ast.FilterFile(typ, file)   // the same, over every document
ast.Parent(root, child)     // the node that holds child
A node pointer does not outlive the walk

Nodes come from an arena that recycles them. A pointer you keep across a walk — AliasNode.Target in particular — can end up naming a different part of the document. Read what you need out of a node while you hold it, rather than storing the node and coming back to it.

Rendering

Node.String() and File.String() render with the defaults. ast.NewRenderer configures it:

var buf bytes.Buffer
r := ast.NewRenderer(ast.WithComments(true), ast.WithIndent(4))
if err := r.Render(&buf, f.Docs[0].Body); err != nil {
	// ...
}

The options are WithComments, WithIndent, WithIndentSequence and WithAliasTargets. The encoder drives this same renderer, which is why encoding and rendering a tree agree.

Merging

ast.Merge merges one node into another. ast.MergeOf reads a *MappingValueNode and reports whether it is a merge and what it merges — ast.MergeEntry and ast.Verdict carry the answer. See merge keys for what fires at which version.

The size of this package

go doc -all ./ast renders over 300 entries, four times any other package here — roughly one node type per shape, each with a full method set. Most programs need Node, MappingNode, MappingValueNode, SequenceNode, the scalars, Walk and the renderer. The rest is there for the parser and the encoder.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Tokens

Where a token comes from

There is no exported tokenizer. A token reaches you from a node:

tk := node.GetToken()

The scanner lives at internal/scanner, under the parser, so token is a type you read rather than a stream you drive.

What a token holds

Valuethe meaningful text, with the syntax taken off
Typewhich lexical kind — StringType, DoubleQuoteType, LiteralType, IntegerType, and so on
PositionLine, Column, and Offset()

Value is processed and the source is not. For name: "pet store" the value token has Value == "pet store"; the quotes are gone.

Addressing the source

Position.Offset() counts bytes from 0 and Token.EndOffset() ends the token, so src[off:end] is the token as written:

p := tk.Position
fmt.Printf("%q\n", src[p.Offset():tk.EndOffset()])
tokenValuesrc[Offset():EndOffset()]
name"name""name"
"pet store""pet store""\"pet store\""
a literal block’s body"two\nlines\n""two\n lines\n"

That third row is the useful one: Value has the block folded and re-indented, and the offsets still address the bytes the document actually carried, indentation included.

Line and Column count from 1 and count characters, because characters are what YAML measures indentation in. Position.IndentNum() gives the indentation the token sits at.

Note

Offsets address the token for 97.1% of the YAML Test Suite’s tokens, and line and column for 94.2%. Two kinds of token are still reported early. Reconstructing a document byte for byte is a target, not a feature, and those percentages are the distance to it.

A block scalar splits over two nodes

ast.LiteralNode.Start is the header token — | or >, with any chomping indicator. The content is a separate node, and its token carries the folded text and the offsets of the raw lines.

Reading a scalar spelling without a document

The functions that turn YAML’s scalar text into Go values are exported, so you can use them on a string you got some other way:

token.ParseInteger("0x1F", token.HexIntegerType)  // 31, true
token.ParseInteger("1_000", token.IntegerType)    // 1000, true
token.ToNumber("1.5e3")                            // {Type:float Value:1500 Text:1.5e3}

ParseInteger returns an int64 where the text carries a sign and a uint64 where it does not. ParseBool, ParseFloat, ParseWholeNumber and ParseTimestamp cover the rest, and ParseBigInteger and ParseBigFloat handle what does not fit a machine word. ToNumber reports the base it read as well as the value.

Deciding whether a scalar needs quoting

Two functions, and the names do not tell them apart:

asks
IsNeedQuoted(v)would a plain scalar spelling v be read back as something else? "yes", "1.0" and "a: b" all say true.
NeedsQuotedSpelling(v)does v hold a character only a double-quoted scalar can carry? Exactly two: a carriage return, and U+FEFF.

So IsNeedQuoted("yes") is true and NeedsQuotedSpelling("yes") is false. Use the first to decide about quoting, the second to decide that nothing but double quotes will do.

LiteralBlockHeader(v) gives the header a literal block needs for v — the chomping and indentation indicators.

Tags

token.YAMLTagPrefix is tag:yaml.org,2002:. ReservedTagOf maps a full tag URI to a ReservedTagKeyword such as !!int, and ReservedTagKeywordMap holds the set. token.Schema names the resolution schema — see YAML versions and tags.

Two constructors for every token

token.Alias(org string, pos) returns a *Token; token.MakeAlias[T Text](org T, pos) returns a Token by value, over a string or a []byte. There is such a pair for about twenty token kinds. They differ in where the token is allocated, not in what it means. If you are building tokens — which mostly means building a tree by hand — either family works; the value form lets the parser fill an arena instead of allocating one token at a time.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

YAMLPath

Reading a value by path

yml := `
store:
  book:
    - author: john
      price: 10
    - author: ken
      price: 12
  bicycle:
    color: red
    price: 19.95
`

path, err := expressions.PathString("$.store.book[*].author")
if err != nil {
	// ...
}

var authors []string
if err := path.Read(strings.NewReader(yml), &authors); err != nil {
	// ...
}
fmt.Println(authors) // [john ken]

The syntax

$the root
.a child
..recursive descent
[n]element n of a sequence
[*]every element of a sequence

A key containing . or * goes in single quotes: $.foo.'bar.baz-*'.hoge. A single quote inside that is escaped with a backslash.

expressions.PathBuilder builds the same paths in code — Root, Child, Index, IndexAll, Recursive, then Build — which is what you want when a segment comes from a variable rather than a literal.

Annotating the source

AnnotateSource returns the lines around the node, with a caret under it:

path, _ := expressions.PathString("$.a")
source, err := path.AnnotateSource([]byte(yml), false)
>  2 | a: 1
          ^
   3 | b: "hello"

The boolean is colored. Use it to report on a value your own code rejected after a successful decode — see Errors.

The godoc does not show the whole type

expressions.Path embeds an unexported engine, so go doc and pkg.go.dev list only Read and Filter. AnnotateSource, String, FilterNode, ReadNode and the merge and replace methods are promoted, callable, and invisible in the rendered documentation — the type’s own doc comment links to [Path.AnnotateSource], and that link goes nowhere.

Until that is fixed, this page is the list.

Working on nodes rather than values

Read and Filter go through the decoder and hand you a Go value. ReadNode and FilterNode stop at the tree, which is what you want when the document is the thing you are changing.

Errors

Four predicates, matching four sentinels: IsInvalidPathError, IsInvalidPathStringError, IsInvalidQueryError, IsNotFoundNodeError. A path that matches nothing is ErrNotFoundNode, not an empty result.

The same path strings key a CommentMap — see Comments.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

The JSON bridge

Converting

j, err := codec.ToJSON([]byte("a: 1\nb: [x, y]\n"))
// {"a": 1, "b": ["x", "y"]}

FromJSON goes the other way. Both are re-exported from the root package, where they take no options; codec.ToJSON takes parser options.

ToJSON walks the document and writes JSON as it reaches each node. Nothing is decoded into a Go value on the way, so a type Go cannot hold does not stop the conversion — and a document too large to model as Go values still converts.

What it refuses

JSON cannot express everything YAML can, and ToJSON reports rather than guesses:

[3:4] JSON has no number for .inf
   1 | a: 1
   2 | b: [x, y]
>  3 | c: .inf
          ^
[1:3] a sequence cannot be a JSON key
>  1 | ? [a,b]
         ^
   2 | : 1

The errors carry a position, so they print like any other — see Errors.

A non-string scalar key is stringified, which can produce a duplicate JSON name: '1.0': 1 and !!float 1: 2 are two YAML keys and one JSON name. parser.WithJSONCompatible reports that pair as ErrNotJSON rather than letting it through.

Go values from a tree

codec.NodeToValue fills a Go value from a node you already have, and ValueToNode builds a subtree from a Go value. To read a source straight to any, call yaml.Unmarshal with a *any: the decoder then builds the values as the parser reads the document and builds no tree.

Conformance

ToJSON scores 272 of 274 on the YAML Test Suite, against 371 of 371 through the decoder — see Conformance.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Decoding into Go values

Everything on these pages is reachable from codec. The root package re-exports Marshal, Unmarshal, ToJSON and FromJSON; anything with options lives in codec.

  • The three entry points, the two constructors, and the interfaces a type can implement to control its own encoding.
  • What yaml:"..." means, what json:"..." means, and the two options that decide whether the second one is read at all.
  • The nineteen DecodeOptions, grouped by what they change, and the four that do nothing on their own.
  • The seventeen EncodeOptions: layout, quoting, what is left out, anchors and comments.
  • Declaring an anchor, referring to it, merging one mapping into another — and the two places where the default does not do what the document says.
  • Reading a document’s comments and writing them back, through a map keyed by path.
  • What the library returns when a document is wrong, and how to print it with the offending line underneath.
Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Subsections of Decoding into Go values

Marshal and Unmarshal

Encode

var v struct {
	A int
	B string
}
v.A = 1
v.B = "hello"

out, err := yaml.Marshal(v)
if err != nil {
	// ...
}
fmt.Println(string(out)) // "a: 1\nb: hello\n"

A field with no tag is written under its Go name, lowercased. That is go.yaml.in/yaml/v3’s rule, and it is the default here — see Struct tags for the two options that change it.

Decode

yml := `
%YAML 1.2
---
a: 1
b: c
`
var v struct {
	A int
	B string
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
	// ...
}

The three entry points, and when each one

calluse it when
yaml.Marshal / yaml.Unmarshalyou need no options
codec.MarshalWithOptions / codec.UnmarshalWithOptionsyou need options for one call
codec.NewEncoder / codec.NewDecoderyou are reading or writing a stream, or reusing the options

The root package re-exports only Marshal and Unmarshal. Everything that takes an option lives in codec.

Reading a stream of documents

A YAML stream holds any number of documents, separated by ---. Decoder.Decode reads one per call and returns io.EOF when the stream ends:

dec := codec.NewDecoder(r)
for {
	var v Config
	err := dec.Decode(&v)
	if errors.Is(err, io.EOF) {
		break
	}
	if err != nil {
		return err
	}
	// ...
}

Documents in one stream are independent: an anchor declared in one is not visible from the next. See Anchors and aliases.

Letting a type encode itself

Five interfaces: two pairs, and NodeUnmarshaler. Implement one of the first two on your type and the codec calls it instead of using reflection.

interfaceyou return / receivemodelled on
codec.Marshaler / codec.UnmarshalerYAML text, as []byteencoding/json
codec.GoYAMLMarshaler / codec.GoYAMLUnmarshaleranother Go valuegopkg.in/yaml.v2

codec.NodeUnmarshaler receives an ast.Node rather than bytes, and a type with an IsZero() bool method — codec.IsZeroer, which time.Time satisfies — decides what omitempty skips.

The two families differ in cost, not in meaning. Indentation is significant in YAML, so a fragment returned by a codec.Marshaler cannot be spliced into its parent as text — the encoder has to parse it back to work out how to place it. A codec.GoYAMLMarshaler returns a Go value and skips that parse. For a type marshalled in a loop, prefer the second; for a config file written once, the first is easier to write.

Registering a marshaler for a type you do not own

codec.CustomMarshaler[T] and codec.CustomUnmarshaler[T] take a function for one type, as an option on one call. codec.RegisterCustomMarshaler[T] does the same globally, for every call in the process — which is why two packages registering for the same type is a conflict neither can see. Prefer the option.

Ordered mappings

codec.MapSlice is a []codec.MapItem, and it decodes and encodes in document order where a Go map cannot. Use it when order matters and the document is still going through the codec; when order matters and the rest of the document does too, work on the document instead.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Struct tags

The default is go.yaml.in/yaml/v3, exactly

A field with no yaml tag is named after its Go field, lowercased. A json tag is not read.

A json tag alone does nothing
type J struct {
	A int `json:"foo"`
}

var j J
codec.Unmarshal([]byte("foo: 1\n"), &j)  // err == nil, j.A == 0

The document says foo, the field wants a, nothing matches, and the decode succeeds. There is no error and no warning. The same struct marshals to a: 7, not foo: 7.

That is v3’s model, and a 35-row parity table in the test suite holds it against v3 itself. If you want encoding/json’s model, ask for it.

Three naming layers, behind two booleans

optionwhat it adds
(default)the yaml tag, else the lowercased Go name — v3’s model
UseJSONTags(true)the json tag is read, the way encoding/json reads it
UseInferredNames(true)an untagged field takes its Go name verbatim, the way encoding/json does

When a field carries both tags, yaml wins:

type Both struct {
	A int `yaml:"ya" json:"ja"`
}
// "ya: 2\nja: 3\n" gives A == 2, with or without UseJSONTags.

The encoder has the mirror pair, WriteJSONTags and WriteInferredNames.

Note

The two directions are separate options. Setting UseJSONTags on a decode without setting WriteJSONTags on the matching encode gives you an asymmetric round trip, and nothing reports it.

The tag itself

type T struct {
	Name    string            `yaml:"name"`
	Skipped string            `yaml:"-"`
	Inner   Embedded          `yaml:",inline"`
	Extra   map[string]string `yaml:",inline"`
	Flow    []int             `yaml:"flow,flow"`
	Maybe   string            `yaml:"maybe,omitempty"`
	Zero    time.Time         `yaml:"zero,omitzero"`
	Def     *Person           `yaml:"default,anchor"`
	Use     *Person           `yaml:",inline,alias"`
}
optioneffect
-the field is never read or written
,inlinean embedded struct’s fields, or a map’s entries, sit in the parent mapping
,flowwritten in flow style: [1, 2, 3]
,omitemptynot written when empty, or when IsZero() says so
,omitzeronot written when the Go zero value
,anchorwritten with an anchor — see Anchors and aliases
,aliaswritten as an alias to a matching anchor

The tag name is yaml, spelled by codec.StructTagName.

AllowFieldPrefixes accepts a key that begins with one of the prefixes you give it. There is no counterpart on the encoder, so a document read that way does not round-trip.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Decode options

Options go to codec.UnmarshalWithOptions for one call, or to codec.NewDecoder for a decoder you keep.

Strictness

optioneffect
DisallowUnknownField()a key matching no exported field is an error
AllowFieldPrefixes(p...)a key beginning with one of p escapes that check
AllowDuplicateMapKey()a repeated key is accepted; the last one wins
Validator(v)runs a StructValidator over the decoded struct
Strict()only DisallowUnknownField
Strict() is one option, not a posture

Strict() enables DisallowUnknownField and nothing else. It does not refuse duplicate keys — those are refused by default — and it does not tighten type conversion. Read it as an alias, not as a mode.

Naming

UseJSONTags(bool), UseInferredNames(bool), and AllowFieldPrefixes again. See Struct tags — the default reads no json tag at all.

What a value decodes to

optioneffect
UseOrderedMap()an untyped mapping becomes a MapSlice, in document order, instead of a Go map
UseStringKeys()every mapping key reads as text, so 1.5: a into map[any]any gives the string "1.5" rather than float64(1.5)
ShareAliases()an alias decodes to the same Go value as its anchor, not an independent copy
UseJSONUnmarshaler()a type with only UnmarshalJSON gets called, with the YAML converted to JSON first

UseOrderedMap is the answer when order matters and the document still goes through the codec. When the rest of the document matters too, work on the document instead.

Anchors from elsewhere

optioneffect
ReferenceFiles(f...)anchors declared in those files
ReferenceDirs(d...)anchors declared in the YAML files of those directories
ReferenceReaders(r...)the same, from readers
RecursiveDir(bool)ReferenceDirs walks subdirectories

See Anchors and aliases.

The rest

CustomUnmarshaler[T] registers a function for one type, for this decode only. CommentToMap(cm) fills a CommentMap. WithParserOptions(...) passes parser options through — which is how you reach WithYAMLVersion.

Four options that do nothing alone

Nothing in the type of any of these says so, and none of them reports being set without its partner:

optionneeds
RecursiveDir(true)ReferenceDirs
AllowFieldPrefixes(...)DisallowUnknownField
UseInferredNames(true)matters only where no yaml tag names the field
ShareAliases()matters only where the document actually aliases
Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Encode options

Options go to codec.MarshalWithOptions for one call, or to codec.NewEncoder for an encoder you keep.

Layout

optioneffect
Indent(n)spaces per level of mapping nesting; DefaultIndentSpaces is 2
IndentSequence(bool)indents sequence entries under their key
Flow(bool)flow style throughout
UseLiteralStyleIfMultiline(bool)a multiline string is written as a literal block, whatever it contains
UseSingleQuote(bool)prefers ' over " where a string needs quoting
JSON()writes JSON

Encoding {"name": "x", "ports": [80, 443]}:

# default                # IndentSequence(true)
name: x                  name: x
ports:                   ports:
- 80                       - 80
- 443                      - 443
Flow(true)   {name: x, ports: [80, 443]}
JSON()       {"name": "x", "ports": [80, 443]}

Indent does not move sequence entries. They sit at their key’s column unless IndentSequence(true) is also set, so Indent(4) alone changes nothing in a document whose only nesting is a sequence. With both:

a:
    ports:
        - 80

Leaving fields out

optioneffect
OmitEmpty()as if every field carried ,omitempty
OmitZero()as if every field carried ,omitzero

Both are the tag applied to everything, so they are the fallback for a type whose tags you do not control. Prefer the tag where you do.

Numbers

AutoInt() writes a float whose fractional part is zero as an integer. map[string]float64{"a": 1.0} gives a: 1.0 by default and a: 1 with the option.

Note

There is no decode counterpart, so AutoInt breaks the round trip on purpose: a float64(1.0) written as 1 reads back as an integer.

Anchors

optioneffect
WithSmartAnchor()two map values sharing a pointer get an anchor on the first and aliases after; the key name becomes the anchor name, with a suffix on collision
MarshalAnchor(fn)calls fn with each *ast.AnchorNode as it is written

Both find an anchor by the address its value stands at. A document decoded and re-encoded therefore keeps its anchors only where the decode left one value behind two names — which is what ShareAliases does. Without it, encoding writes the shared subtree out twice.

Naming and custom types

WriteJSONTags(bool) and WriteInferredNames(bool) mirror the decode pair — see Struct tags. UseJSONMarshaler() calls a type’s MarshalJSON. CustomMarshaler[T] registers a function for one type, for this encode only.

Comments

WithComment(cm) writes the comments in a CommentMap.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Anchors, aliases and merge keys

Writing an anchor

Tag the field that holds the shared value with ,anchor, and the field that refers to it with ,alias:

type Person struct {
	*Person `yaml:",omitempty,inline,alias"`
	Name    string `yaml:",omitempty"`
	Age     int    `yaml:",omitempty"`
}

defaultPerson := &Person{Name: "John Smith", Age: 20}

var doc struct {
	Default *Person   `yaml:"default,anchor"`
	People  []*Person `yaml:"people"`
}
doc.Default = defaultPerson
doc.People = []*Person{
	{Person: defaultPerson, Name: "Ken", Age: 10},
	{Person: defaultPerson},
}

out, _ := yaml.Marshal(doc)
default: &default
  name: John Smith
  age: 20
people:
- <<: *default
  name: Ken
  age: 10
- <<: *default

codec.MarshalAnchor gives you a callback to name each anchor yourself, and codec.WithSmartAnchor names them from the field.

Reading a merge key

A plain << does nothing under YAML 1.2

<< is a plain scalar that a 1.1 processor resolves to the merge type. YAML 1.2 dropped resolution by scalar shape, and this library follows the schema — so under the 1.2 default << is an ordinary key, the merge never happens, and there is no error.

Writing the tag out says the same thing without relying on resolution, and that is honoured at every version:

written1.21.1
<<: *dnot mergedmerged
!!merge <<: *dmergedmerged

!!merge on any key other than << is refused: could not find merge key.

Decode the document above, exactly as Marshal wrote it:

1.2 default    people[0] = {Name:"Ken" Age:10 Person:nil}
               people[1] = {Name:""    Age:0  Person:nil}

%YAML 1.1      people[0] = {Name:"Ken" Age:10 Person:&{John Smith 20}}
               people[1] = {Name:""    Age:0  Person:&{John Smith 20}}

people[1] is meant to be the default person entire. Under 1.2 it comes back empty.

Use parser.WithMergeKeys() when you have to read documents written this way. It resolves a bare << at any version and changes nothing else:

codec.UnmarshalWithOptions(src, &v,
	codec.WithParserOptions(parser.WithMergeKeys()))
mergea: yesb: 0100
defaultno"yes"100
WithMergeKeys()yes"yes"100
WithYAMLVersion(YAML11)yestrue64

Reading a whole document under 1.1 to get one merge key changes far more than the merge: 0100 becomes 64, 1_000 becomes 1000, 1:30 becomes 90 and yes becomes true. Reach for WithMergeKeys instead, or write !!merge <<: in the document if you control it.

This follows from one rule the library holds everywhere: a written tag is honoured at any version, and only resolution by scalar shape is version-gated. It has a consequence worth knowing before you rely on a round trip — the encoder writes the plain <<, so Marshal produces a document that Unmarshal will not merge unless the reading side passes WithMergeKeys. Other Go libraries resolve << at any version, which is what WithMergeKeys exists to match.

When the merge does fire, the mapping’s own key beats the merged one, and an earlier merge beats a later one.

Reading an alias

By default an alias decodes to an independent value. Given

a: &x {n: 1}
b: *x

a and b are two Go values, and changing one does not change the other. codec.ShareAliases makes them the same value.

Sharing and round-tripping go together

The encoder finds anchors by pointer address. Two independent values are two anchors, so a decode without ShareAliases followed by an encode writes the shared subtree out twice instead of anchoring it once. If you are reading a document in order to write it back, pass ShareAliases.

Anchors declared in another file

codec.ReferenceDirs, ReferenceFiles and ReferenceReaders publish anchors from elsewhere. Given testdata/anchor.yml:

a: &a
  b: 1
  c: hello
dec := codec.NewDecoder(
	bytes.NewBufferString("a: *a\n"),
	codec.ReferenceDirs("testdata"),
)
var v struct {
	A struct {
		B int
		C string
	}
}
if err := dec.Decode(&v); err != nil {
	// ...
}
fmt.Printf("%+v\n", v) // {A:{B:1 C:hello}}

RecursiveDir(true) walks subdirectories; on its own it means nothing.

Anchors do not cross documents

Documents in one stream are independent, so an alias must name an anchor declared in the same document. To reach an anchor from another parse, hand it over with parser.WithAnchors — see the parser.

The alias budget

A document can name one anchor from many aliases, and an anchor can hold a large subtree, so an adversarial document expands enormously. The decoder caps the work and returns errors.NewExcessiveAliasing when a document exceeds it. NewRecursiveAlias and NewUnknownAnchor cover the other two failures.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Comments

Round trip

Ask the decoder to fill a CommentMap, then hand the same map to the encoder:

cm := codec.CommentMap{}

var v map[string]any
if err := codec.UnmarshalWithOptions(src, &v, codec.CommentToMap(cm)); err != nil {
	// ...
}

out, err := codec.MarshalWithOptions(v, codec.WithComment(cm))

Given

# head of doc
name: x   # line on name
# head of ports
ports:
  - 80

the map holds

$.name    Head  [" head of doc"]
$.name    Line  [" line on name"]
$.ports   Head  [" head of ports"]

and the re-encode writes all three back.

What the key is

A YAMLPath string, and the same syntax expressions.PathString takes. Two comments on one path do not collide: the entry is a slice, and each *codec.Comment carries its own CommentPosition — CommentHeadPosition, CommentLinePosition or CommentFootPosition.

codec.HeadComment, LineComment and FootComment build them, which is how you add a comment to a document that had none.

A leading comment belongs to the first key

# head of doc sits above the whole document, and it comes back as the head comment of $.name. There is no key for the document itself.

Paths have to be on

The map is keyed by the node paths the parser records. parser.WithOmitNodePaths stops recording them, and the map then comes back keyed by empty strings, with no error. See the parser.

On the tree instead

parser.WithComments keeps comments on the tree, as ast.CommentNode and ast.CommentGroupNode, reachable through ast.Node.GetComment. That is the layer to use when the comments matter as much as the values — a CommentMap is a projection, and the tree is the document.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Errors

The pretty rendering

Every error carries the token it was raised at, so it can be printed with the source around it. errors.FormatError does that:

fmt.Println(errors.FormatError(err, false, true))
[6:1] cannot use []interface {} as a map key: it is not comparable
   3 | version: 1.2.3
   4 | limits:
   5 |   max: 18446744073709551615
>  6 | ? [a, b]
       ^
   7 | : a sequence used as a key

The two booleans are colored and inclSource. FormatErrorAtToken does the same for a message and a token of your own, which is what you want when your program rejects a document the parser accepted.

Telling one failure from another

Match on the sentinels with errors.Is:

if errors.Is(err, yamlerrors.ErrSyntax) {
	// the document is not YAML
}

Or take the error apart with errors.As and an *errors.Error, which carries the token and therefore the position.

The conditions the library distinguishes: syntax, type mismatch, overflow, duplicate key, unknown field, unknown anchor, recursive alias, excessive aliasing, unhashable key, not-JSON, and unexpected node type.

Pointing at a value your own code rejected

The parse succeeded, your validation did not, and you want the same rendering. Address the value by path and annotate the source:

var v struct {
	A int
	B string
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
	// ...
}
if v.A != 2 {
	path, err := expressions.PathString("$.a")
	if err != nil {
		// ...
	}
	source, err := path.AnnotateSource([]byte(yml), true)
	if err != nil {
		// ...
	}
	fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, source)
}

See YAMLPath for the path syntax.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

YAML versions and tags

The rule

A written tag is honoured at any version. Only resolution by scalar shape is version-gated.

YAML 1.2 did not un-define the tags 1.1 named — it gave an open tag namespace with a set already in it. It dropped the automatic reading of a plain scalar by the shape of its text. So !!bool yes is a bool everywhere, and plain yes is a bool only under 1.1.

Measured

written1.2 (the default)1.1
yes"yes", a stringtrue
!!bool yestruetrue
0777777511, read as octal
<<: *dnot merged, unless parser.WithMergeKeysmerged
!!merge <<: *dmergedmerged
2001-12-14"2001-12-14""2001-12-14"
!!timestamp 2001-12-14time.Timetime.Time
A plain date is never a timestamp

1.1 lists the timestamp among the types every reader resolves, and this library does not resolve it — under either version. Write !!timestamp to get a time.Time. That gap is known and recorded; the rest of the 1.1 schema, its numbers and its booleans, does resolve.

Choosing the version

Per document, from its own directive:

%YAML 1.1
---
a: yes    # true

Or for the decode, as a fallback where the document declares nothing:

codec.UnmarshalWithOptions(src, &v,
	codec.WithParserOptions(parser.WithYAMLVersion(parser.YAML11)))

parser.YAML10, YAML11 and YAML12 are the three. The directive in the document wins over the option.

Warning

The version is a parser.Option, so a codec caller reaches it through WithParserOptions — two hops for something a document declares about itself.

When a tag and the value disagree

!!int abc is an assertion that does not hold, and by default it is an error naming both the text and the tag. parser.WithLaxTags reads the scalar as the text it was written with instead of refusing the document.

Tags this library does not act on

!!pair and !!value are carried and inert. That is deliberate and it is the reversible choice: implementing a tag later changes a value, refusing one changes whether a document reads at all.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

About

  • go-yaml is a hard fork of goccy/go-yaml. What that means, and how it relates to the other YAML libraries in the Go ecosystem.
  • How the library is measured against the YAML specification, and what it scores today.
  • What has been measured, against which baseline, and what the numbers mean for a caller.
  • No release yet, an API that still moves, and the list of what is not built.
Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Subsections of About

The fork

Outline

This page is an outline. The structure is settled; the prose is not written. Most of the material exists in the repository README and moves here.

What the page must answer

  • Why fork rather than contribute upstream?
  • Is there a way back?
  • Which library should I use if I am not go-openapi?

Sections

  • The fork point, and what has changed since
  • Hard fork: no upstream merges, no shared release line
  • Licensing: Apache-2.0 for this repository’s work, with goccy’s MIT notice retained in NOTICE for the code the fork started from
  • The relationship to go.yaml.in/yaml/v3, which the codec’s default struct-tag behaviour matches
  • go-openapi’s reason for owning this: the toolkit needs a YAML implementation it can hold to the specification
Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Conformance

Outline

This page is an outline. The structure is settled; the prose is not written.

Where it stands

suitescoreablepassing
YAML test suite, decoder371371
YAML test suite, ToJSON274272
reference-parser oracle393393

The generated corpus covers 605 buckets over 14684 cases, of which 567 agree with the oracle.

What the page must answer

  • What is being measured, and against what?
  • What does “scoreable” exclude, and why?
  • Where do I look when my document is handled differently from another parser?

Sections

  • The three yardsticks: the YAML test suite, a reference parser used as an oracle, and a generated corpus
  • What is deliberately not conformant, if anything
  • How to report a document that decodes wrongly
Warning

Every number on this page comes from metrics.yaml. Never type a score into prose — use siteparam, so one edit moves every page.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Performance

Outline

This page is an outline. The structure is settled; the prose is not written.

What the page must answer

  • Is this faster than what I use today, and at what?
  • What does it allocate?
  • Which knobs actually change the numbers?

Sections

  • The baseline and the harness, named precisely enough to reproduce
  • Parse, decode and encode, measured separately, because they do not move together
  • Where the work is still open
Warning

A comparison is only worth printing when both sides measure the same thing. Any figure on this page must name its benchmark, so a reader can check what is being timed on each side.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Status

Experimental

There is no tagged release. go get resolves a pseudo-version on master, and the API changes without notice.

What the page must answer

  • Can I depend on this?
  • What is missing that I might expect?
  • Where do I watch for the first release?

Not built

  • Streaming. No API reads a document without holding it. parser.WithChunkSize and WithOnComplete are the seams it will use; neither is a streaming API.
  • A JSON token stream. Designed, not built.
  • Verbatim reconstruction. The AST keeps enough of the source to make it possible; nothing exposes it.
  • A stable comment model on the AST. A caller has CommentMap today and nothing on the tree itself.
Info

This page is the one place on the site allowed to describe what does not exist. Everywhere else, a page describes committed code or says nothing.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Project

This section holds material specific to this repository:

Documentation that applies to every go-openapi repository lives in the shared doc-site:

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

Subsections of Project

README

Outline

This page will carry a copy of the repository README, the way every go-openapi doc site does. One thing has to happen first.

Before this page is filled

The synopsis moves out. Sections 1 to 5 of the README are usage material and belong under Usage and Advanced. Copying the README here today would duplicate them.

The licence question that also held this page is settled: the library is Apache-2.0, and NOTICE records goccy’s MIT terms for the code the fork started from. See The fork.

Last edited by: Frédéric BIDON Nov 18, 2026
Copyright 2015-2025 go-openapi maintainers. This documentation is under an Apache 2.0 license.

LICENSE

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.