跳到主要内容
ansicode
Go

在 Go 中使用 ANSI 转义码

Go 的 `fmt.Print*` 是字节透传的 —— `\x1b[31m` 在 Unix 与 Windows 10+ 上均可工作(需启用 `ENABLE_VIRTUAL_TERMINAL_PROCESSING`,可通过 `golang.org/x/sys/windows` 翻转)。多于少量转义时,请用 `fatih/color`;要构建完整 TUI,请用 Charmbracelet 系列(`lipgloss` + `bubbletea`)。

推荐库

  • github.com/fatih/color

    符合 Go 习惯的颜色库:`color.New(color.FgRed, color.Bold).Println("oops")`。自动检测终端能力并尊重 `NO_COLOR`。

  • github.com/charmbracelet/lipgloss

    为终端输出设计的 CSS 风格样式 DSL(margin、padding、边框、拼接)。基于 `termenv`,最终渲染为纯 ANSI 字节。

  • github.com/charmbracelet/bubbletea

    采用 Elm 架构的 TUI 框架 —— model / update / view。配合 lipgloss 做样式、bubbles 提供现成组件。

  • github.com/muesli/termenv

    较低层的能力检测 —— 终端背景色、配置档(TrueColor / ANSI 256 / ANSI 16)、备用屏幕、鼠标、括号粘贴。

常用写法

使用 fmt 直接输出字节
package main

import "fmt"

func main() {
    fmt.Println("\x1b[1;31merror:\x1b[0m permission denied")
}
使用 fatih/color 输出颜色
package main

import "github.com/fatih/color"

func main() {
    red := color.New(color.FgRed, color.Bold)
    red.Println("error: permission denied")
}
用 defer 进入 / 退出备用屏幕
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Print("\x1b[?1049h")          // enter alt screen
    defer fmt.Print("\x1b[?1049l")    // leave on return
    fmt.Print("painted in alt buffer")
    time.Sleep(2 * time.Second)
}
Truecolor RGB 前景色
package main

import "fmt"

func main() {
    // \x1b[38;2;R;G;Bm — SGR 38;2 = direct RGB foreground
    fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m\n", 0xcb, 0xa6, 0xf7, "lavender")
}

相关序列

其他语言