Thanks to visit codestin.com
Credit goes to github.com

Skip to content

afeiship/go-box

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-box

Simple ASCII box drawing for Go CLI apps with Unicode support and runewidth optimization.

installation

go get -u github.com/afeiship/go-box

usage

package main

import "github.com/afeiship/go-box"

func main() {
	// 🎉 极简使用
	lines := []string{
		"✅ Hello, World!",
		"🚀 Go is awesome!",
	}
	box.PrintBox(lines)

	// 🎨 自定义样式
	opts := box.DefaultBoxOptions()
	opts.BorderStyle = "double"  // round, double, ascii
	opts.Padding = 1
	opts.Indent = 2
	box.PrintBoxWithOptions(lines, opts)

	// 📱 ASCII 框样式
	box.PrintASCIIBox(lines)

	// 🌈 带颜色的文本
	coloredLines := []string{
		"\x1b[31m🔴 错误信息\x1b[0m",
		"\x1b[32m🟢 成功信息\x1b[0m",
		"\x1b[33m🟡 警告信息\x1b[0m",
	}
	box.PrintBox(coloredLines) // 完美对齐,忽略 ANSI 颜色码
}

效果预览:

┌──────────────────────┐
│ ✅ Hello, World!     │
│ 🚀 Go is awesome!    │
└──────────────────────┘

  ╔═════════════════════════════╗
  ║                             ║
  ║ ✅ Hello, World!            ║
  ║ 🚀 Go is awesome!           ║
  ║                             ║
  ╚═════════════════════════════╝

+------------------------+
| ✅ Hello, World!     |
| 🚀 Go is awesome!    |
+------------------------+

┌─────────────────┐
│ 🔴 错误信息      │
│ 🟢 成功信息      │
│ 🟡 警告信息      │
└─────────────────┘

🎨 边框样式

go-box 支持多种边框样式:

1. round (默认)

使用 Unicode 圆角字符,适合大多数现代终端。

┌──────────────────────┐
│ ✅ Hello, World!     │
└──────────────────────┘

2. double

使用 Unicode 双线字符,更加醒目。

╔══════════════════════╗
║ ✅ Hello, World!     ║
╚══════════════════════╝

3. ascii ⭐ 新增

使用纯 ASCII 字符,兼容性最好,适用于任何终端。

+------------------------+
| ✅ Hello, World!     |
+------------------------+

⚡ 优化特性

🎯 精确的 Unicode 宽度计算

使用 github.com/mattn/go-runewidth 进行精确的字符串宽度计算,支持:

  • Emoji 字符 (🚀, ✅, 📦) - 2 列宽度
  • 中文字符 - 2 列宽度
  • ANSI 颜色码 - 自动过滤,不影响对齐
  • 各种 Unicode 特殊字符

🧹 自动 ANSI 清理

自动过滤 ANSI 颜色转义序列,确保框边框完美对齐,即使在有颜色的文本中也能正常工作。

📋 API 参考

PrintBox(lines []string)

使用默认的 round 样式打印框。

PrintASCIIBox(lines []string) ⭐ 新增

使用 ASCII 样式打印框的便捷函数。

PrintBoxWithOptions(lines []string, opts *BoxOptions)

使用自定义选项打印框。

选项配置:

type BoxOptions struct {
    Padding     int    // 内边距
    BorderStyle string // 边框样式: "round", "double", "ascii"
    Indent      int    // 缩进空格数
}