Recursive AI

Read and write binary YAML as a Go byte slice

oneyaml-go is a free, open-source YAML library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.

!!binary is YAML’s tag for raw bytes stored as Base64 text. Marshal a []byte to write !!binary; unmarshal into a []byte to get the original bytes back.

Terminal
go get oneyaml.dev/go
GO
package main
 
import (
	"bytes"
	"fmt"
 
	yaml "oneyaml.dev/go"
)
 
func main() {
	original := []byte{0x00, 0x7f, 0xff}
	text, err := yaml.Marshal(original)
	if err != nil {
		panic(err)
	}
	var decoded []byte
	err = yaml.Unmarshal(text, &decoded)
	if err != nil {
		panic(err)
	}
	fmt.Print(string(text))
	fmt.Printf("Bytes: % x\n", decoded)
	equal := bytes.Equal(original, decoded)
	fmt.Println("Equal:", equal)
}

Unzip the example, then go run ..

Text
!!binary AH//
Bytes: 00 7f ff
Equal: true

Requires Go 1.24 or later. Run go get inside a Go module.

The source bytes include 00 and ff, so comparing the decoded bytes checks more than visible text would. If a tagged scalar contains invalid Base64, Unmarshal into []byte returns an error.

Variations

If the binary value is one field in a larger mapping, use a []byte field. This input produces the same three bytes:

GO
var cfg struct {
    Data []byte `yaml:"data"`
}
input := []byte("data: !!binary AH//\n")
if err := yaml.Unmarshal(input, &cfg); err != nil {
    panic(err)
}
fmt.Printf("Bytes: % x\n", cfg.Data)

The short answer

Give oneyaml-go a []byte when calling Marshal and a pointer to a []byte when calling Unmarshal. The writer emits a tagged scalar such as !!binary AH//. The reader decodes the payload into the original bytes when the target is a byte slice. Compare the result with bytes.Equal rather than comparing Base64 strings.

What is the difference between binary data and Base64 data?

Binary data is the original sequence of bytes. Base64 represents those bytes as text using a restricted alphabet. In YAML, the !!binary type uses Base64 as its text representation. AH// is what you see in the file; 00 7f ff is what you use in Go. Marshal the original byte slice, not a slice containing an already encoded Base64 string, or the bytes encoded in the YAML will be those of the Base64 text rather than the original data.

Does a plain Base64 string decode into a Go byte slice?

Not automatically. For an ordinary scalar, a []byte target gets the bytes of its text. Tagged !!binary AH// gives 00 7f ff; untagged AH// gives the bytes for the four characters A, H, /, and /. The pinned decoder documentation also distinguishes typed and generic reads: decoding into any retains the Base64 text as a string. If you know a value is binary, use a byte slice or a typed field so the parser knows to decode it.

All oneyaml Go recipes