Introduction to the
Here’s a simpler one: 😀. Termtables handles the output of tabular data. It is applicable to output some status or statistical data anytime and anywhere for easy observation and debugging. It’s a very small tool library. I came across this library occasionally while studying the Dateparse library.
Quick to use
The code in this article uses Go Modules.
Create directory and initialize:
$ mkdir termtables && cd termtables
$ go mod init github.com/darjun/go-daily-lib/termtables
Copy the code
Install the Termtables library:
$ go get -u github.com/scylladb/termtables
Copy the code
The most primitive termtables library for github.com/apcera/termtables, then the original warehouse has been deleted. Currently, it’s all someone else’s fork’s warehouse.
Use:
package main
import (
"fmt"
"github.com/scylladb/termtables"
)
func main(a) {
t := termtables.CreateTable()
t.AddHeaders("User"."Age")
t.AddRow("dj".18)
t.AddRow("darjun".30)
fmt.Println(t.Render())
}
Copy the code
Run:
$ go run main.go
+--------+-----+
| User | Age |
+--------+-----+
| dj | 18 |
| darjun | 30 |
+--------+-----+
Copy the code
It’s easy to use by calling termtables.createtable () to create a table object, calling the object’s AddHeader() method to AddHeader information, and then calling AddRow() to add data row by row. The final call to Render() returns the rendered table string.
model
Working with plain text tables, TermTables also supports output of tables in HTML and Markdown formats. Just call the SetModeHTML()/SetModeMarkdown() methods of the table object to set some patterns.
func main(a) {
t := termtables.CreateTable()
t.AddHeaders("User"."Age")
t.AddRow("dj".18)
t.AddRow("darjun".30)
fmt.Println("HTML:")
t.SetModeHTML()
fmt.Println(t.Render())
fmt.Println("Markdown:")
t.SetModeMarkdown()
fmt.Println(t.Render())
}
Copy the code
Run:
$ go run main.go
HTML:
<table class="termtable">
<thead>
<tr><th>User</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>dj</td><td>18</td></tr>
<tr><td>darjun</td><td>30</td></tr>
</tbody>
</table>
Markdown:
| User | Age |
| ------ | --- |
| dj | 18 |
| darjun | 30 |
Copy the code
The output format can be used directly in Markdown/HTML files.
conclusion
Let’s relax today and learn about termtables, a small tool library. While it’s not complicated to implement a similar one ourselves, the TermTables library takes care of the tedious details of encoding, word width, and so on. If you need to print table-like data in your sample program, try Termtables.
If you find a fun and useful Go library, please Go to GitHub and submit issue😄
reference
- GitHub: github.com/darjun/go-d…
- Termtables GitHub:github.com/scylladb/te…
I
My blog is darjun.github. IO
Welcome to follow my wechat public account [GoUpUp], learn together, progress together ~