How to Parse and Generate HTML in Go (golang.org/x/net/html)

Use the `golang.org/x/net/html` package to parse HTML into a tree of nodes and generate HTML by walking that tree. The parser returns a `*html.Node` representing the document root, which you can traverse recursively to read or modify content, then serialize back to a string using `html.Render`.

How to Parse and Generate HTML in Go (golang.org/x/net/html)

Use the golang.org/x/net/html package to parse HTML into a tree of nodes and generate HTML by walking that tree. The parser returns a *html.Node representing the document root, which you can traverse recursively to read or modify content, then serialize back to a string using html.Render.

package main

import (
	"bytes"
	"fmt"
	"os"
	"strings"

	"golang.org/x/net/html"
)

func main() {
	// Parse HTML
	doc, err := html.Parse(strings.NewReader("<html><body><p>Hello</p></body></html>"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "parse error: %v\n", err)
		os.Exit(1)
	}

	// Generate HTML by rendering the node tree
	var buf bytes.Buffer
	if err := html.Render(&buf, doc); err != nil {
		fmt.Fprintf(os.Stderr, "render error: %v\n", err)
		os.Exit(1)
	}
	fmt.Println(buf.String())
}

Note: The example above requires importing "strings" and "bytes" from the standard library.