Golang:如何为 fmt.Fprintf 输出着色?

Golang: How to color fmt.Fprintf output?

我知道我可以为 fmt.Println 输出添加颜色,例如:

package main

import (
    "fmt"
)

func main() {
    colorReset := "3[0m"
    colorRed := "3[31m"
    fmt.Println(string(colorRed), "test", string(colorReset))
    fmt.Println("next")
}

有什么方法可以为 fmt.Fprintf 的输出着色?

与您使用 Println 的方式相同,您可以通过 Fprintf 使用颜色,ex

const colorRed = "3[0;31m"
const colorNone = "3[0m"

func main() {
    fmt.Fprintf(os.Stdout, "Red: 3[0;31m %s None: 3[0m %s", "red string", "colorless string")
    fmt.Fprintf(os.Stdout, "Red: %s %s None: %s %s", colorRed, "red string", colorNone, "colorless string")
}