去提问»
提问背景 Question:
undefined: highlighting.WithFormatters [linux] 现在是这样了。

解决Goldmark编译报错

发布时间:2026-08-18 13:57 👁️ 阅读:2

这个错误是因为在 github.com/yuin/goldmark-highlighting/v2 中,根本不存在 highlighting.WithFormatters 这个函数。这是一个常见的拼写或版本混淆错误。

goldmark-highlighting/v2 中,用来传递 Chroma 渲染参数的正确 Option 函数是 highlighting.WithFormatOptions

解决方案

请将你的代码修改为以下完整且兼容的写法。注意检查你的 import 路径,确保全部统一使用 v2 版本。

1. 正确的 Go 代码实现

package main

import (
	"bytes"
	"html/template"

	// 1. 必须使用 v2 版本的 chroma html formatter
	chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/yuin/goldmark"
	// 2. 必须使用 v2 版本的 goldmark-highlighting
	highlighting "github.com/yuin/goldmark-highlighting/v2"
)

func ConvertMarkdown(mdContent string) template.HTML {
	// 初始化 Goldmark,并加载高亮插件
	markdown := goldmark.New(
		goldmark.WithExtensions(
			highlighting.NewHighlighting(
				highlighting.WithStyle("monokai"), // 设置代码高亮主题(例如 monokai, github, dracula 等)
				
				// 注意:这里是 WithFormatOptions,而不是 WithFormatters!
				highlighting.WithFormatOptions(
					chromahtml.WithLineNumbers(true), // 开启行号
					// chromahtml.WithClasses(true),  // 若使用自定义CSS,可开启此行
				),
			),
		),
	)

	var buf bytes.Buffer
	if err := markdown.Convert([]byte(mdContent), &buf); err != nil {
		// 如果解析失败,则回退返回原始未渲染的内容
		return template.HTML(mdContent)
	}

	return template.HTML(buf.String())
}

2. 为什么会报错?

  1. API 名称错误goldmark-highlighting 库的设计者提供的方法是 WithFormatOptions(用于包装 Chroma 自身的 HTML 渲染选项),而非 WithFormatters
  2. 库版本不一致:如果将老版本的 chroma(没有 v2)与新版的 goldmark-highlighting/v2 混合引入,会产生编译期类型不匹配错误。通过将 chromahtml 显式指向 github.com/alecthomas/chroma/v2/formatters/html,即可彻底解决此兼容性问题。

3. 依赖检查

在终端执行以下命令,确保依赖已正确载入到你的 go.mod 中:

go get github.com/yuin/goldmark-highlighting/v2
go get github.com/alecthomas/chroma/v2/formatters/html
go mod tidy