Decode MIME Headers And Dot Blocks With textproto

Parse MIME headers with net/textproto ReadMIMEHeader and decode dot-stuffed text blocks via DotReader, stopping cleanly at the terminator line.

GoData Integrity

Code

snippet
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"net/textproto"
	"strings"
)

func readFrame(raw string) error {
	r := textproto.NewReader(bufio.NewReader(strings.NewReader(raw)))
	hdr, err := r.ReadMIMEHeader()
	if err != nil {
		return fmt.Errorf("headers: %w", err)
	}
	body, err := io.ReadAll(r.DotReader())
	if err != nil {
		return fmt.Errorf("dot body: %w", err)
	}
	next, _ := r.ReadLine()
	fmt.Printf("trace-id=%s received=%v\n", hdr.Get("x-trace-id"), hdr.Values("Received"))
	fmt.Printf("body=%q\n", string(body))
	fmt.Printf("after-terminator=%q\n", next)
	return nil
}

func main() {
	msg := strings.Join([]string{
		"x-trace-id: req-904",
		"Received: hop-1",
		"Received: hop-2",
		"",
		"first line",
		"..escaped leading dot",
		".",
		"QUIT",
	}, "\r\n") + "\r\n"

	if err := readFrame(msg); err != nil {
		fmt.Println("unexpected error:", err)
	}

	truncated := "Subject: partial\r\n\r\nhello without dot\r\n"
	err := readFrame(truncated)
	fmt.Println("missing terminator:", errors.Is(err, io.ErrUnexpectedEOF), err)
}

Mechanics trace — Decode MIME Headers And Dot Blocks With textproto

Execution behavior runs exclusively within helpers readFrame and main.

Error handling is inline: 3 places test err != nil and branch immediately.

Caveats

  • Zero installs necessary because standard library calls handle the entire example cleanly.
  • There are no exceptions to catch — err return values must be checked at each call site.

Applying it

The entry-point signature is func readFrame(raw string) error

The run emits 5 labeled sections — trace-id=, body=, after-terminator=, unexpected error:, missing terminator: — one per step.

The demo flow inside main is readFrame — run the file to see it end to end.

Statements that matter

return fmt.Errorf("dot body: %w", err)
return fmt.Errorf("headers: %w", err)

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As returned `error` values — 3 sites in the snippet check `err` before using other results.
What does Decode MIME Headers And Dot Blocks With textproto print when run?
No setup needed: run the file and look for labeled lines like `trace-id=`, `body=`, `after-terminator=` in the output.