Pass the destination to NewEncoder. The same code can write to a terminal, a file, or another io.Writer.
go get oneyaml.dev/goRequires Go 1.24+. The import path is oneyaml.dev/go, and the package name is oneyaml.
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 ..
replicas: 2Encode 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, 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.
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:
config["replicas"] = 3 if err := enc.Encode(config); err != nil { log.Fatal(err) }
replicas: 2 --- replicas: 3
Related recipes
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 is anything with a Write(p []byte) (n int, err error) method that follows the interface’s contract. An *os.File writes to a file or another open descriptor, and a *bytes.Buffer 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 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 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, flush that wrapper and check the flush error before closing the file.