---
title: "Encode YAML to an io.Writer in Go"
url: https://recursiveai.org/oneyaml/go/cookbook/write-yaml-to-io-writer/
description: "Use NewEncoder to write YAML to an io.Writer in Go. Send a document to stdout or a file, or write multiple documents to one stream."
version: "1.0.0"
---

# Encode YAML to an io.Writer in Go

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

[pkg.go.dev](https://pkg.go.dev/oneyaml.dev/go) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-go) · [Docs](https://recursiveai.org/oneyaml/go/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/go/cookbook/write-yaml-to-io-writer/write-yaml-to-io-writer.zip)

Pass the destination to `NewEncoder`. The same code can write to a terminal, a file, or another `io.Writer`.

```shell
go get oneyaml.dev/go
```

Requires Go 1.24+. The import path is `oneyaml.dev/go`, and the package name is `oneyaml`.

```go
package main

import (
    "log"
    "os"

    "oneyaml.dev/go"
)

func main() {
    enc := oneyaml.NewEncoder(os.Stdout)
    config := map[string]int{
        "replicas": 2,
    }
    err := enc.Encode(config)
    if err != nil {
        log.Fatal(err)
    }
}
```

Save this program as `main.go` in your Go module, then run `go run .`.

```text
replicas: 2
```

`Encode` returns an error if the value cannot be encoded or the destination’s `Write` fails. If writing fails, the destination may already contain part of the document.

Unzip [the example](https://recursiveai.org/oneyaml/go/cookbook/write-yaml-to-io-writer/write-yaml-to-io-writer.zip), then `go run .`.

## Variations

**Write a YAML file.** Replace `main` with this version. It creates or truncates `config.yaml`, encodes to the open file, and checks the file’s close error separately.

```go
func main() {
    file, err := os.Create("config.yaml")
    if err != nil {
        log.Fatal(err)
    }
    enc := oneyaml.NewEncoder(file)
    config := map[string]int{"replicas": 2}
    writeErr := enc.Encode(config)
    closeErr := file.Close()
    if writeErr != nil {
        log.Fatal(writeErr)
    }
    if closeErr != nil {
        log.Fatal(closeErr)
    }
}
```

**Write two documents to the same stream.** Add this after the first successful `Encode` in the snippet at the top:

```go
config["replicas"] = 3
if err := enc.Encode(config); err != nil {
    log.Fatal(err)
}
```

```text
replicas: 2
---
replicas: 3
```

## Related recipes

- [Write a struct to a YAML file](https://recursiveai.org/oneyaml/go/cookbook/write-yaml/)
- [Read a multi-document Kubernetes YAML file](https://recursiveai.org/oneyaml/go/cookbook/kubernetes-multi-document/)

## The short answer

Call `oneyaml.NewEncoder(writer).Encode(value)` to send a Go value as YAML to an `io.Writer`. Handle the error from `Encode`. The example sends YAML to `os.Stdout`; pass an open file or `&bytes.Buffer` instead to change the destination without changing the value you encode.

## What is an `io.Writer` in Go?

An [`io.Writer`](https://pkg.go.dev/io#Writer) is anything with a `Write(p []byte) (n int, err error)` method that follows the interface’s contract. An [`*os.File`](https://pkg.go.dev/os#File.Write) writes to a file or another open descriptor, and a [`*bytes.Buffer`](https://pkg.go.dev/bytes#Buffer.Write) holds the bytes in memory. Use the encoder when you already have a destination. Use `Marshal` instead when the result you need is a `[]byte` that you’ll pass around yourself. The [encoder](https://github.com/recursive-ai-oss/oneyaml-go/blob/7a4c8e39f041b945ee5f121c055f03bc2d7d01d9/marshal.go#L112-L129) prepares each document before it calls `Write`, so it won’t write a document whose value fails to encode. That doesn’t make the destination write atomic.

## How do you write multiple YAML documents to one stream in Go?

Call `Encode` once per value on the **same** encoder. It inserts a `---` before each document after the first. A slice passed to one call produces one document containing a sequence instead. Don’t create a fresh encoder per value on the same writer if you need those separators.

[`Encoder.Close`](https://github.com/recursive-ai-oss/oneyaml-go/blob/7a4c8e39f041b945ee5f121c055f03bc2d7d01d9/marshal.go#L132-L137) ends the encoder stream: subsequent calls to `Encode` return an error. It doesn’t close the underlying writer. If you opened the destination file, close it yourself. If you wrapped it in a [`bufio.Writer`](https://pkg.go.dev/bufio#Writer.Flush), flush that wrapper and check the flush error before closing the file.
