3

Introduction

Today, learn a little bit simpler 😀, termtables deal with the output of table form data. It is suitable for outputting some status or statistical data anytime and anywhere, which is convenient for observation and debugging. It is a very small tool library. I came across this library occasionally when I was learning dateparse

Quick to use

The code in this article uses Go Modules.

Create a directory and initialize:

$ mkdir termtables && cd termtables
$ go mod init github.com/darjun/go-daily-lib/termtables

Install the termtables library:

$ go get -u github.com/scylladb/termtables

The original termtables library is github.com/apcera/termtables , and the original warehouse has been deleted. Currently, the warehouses of other people's forks are used.

use:

package main

import (
  "fmt"
  "github.com/scylladb/termtables"
)

func main() {
  t := termtables.CreateTable()
  t.AddHeaders("User", "Age")
  t.AddRow("dj", 18)
  t.AddRow("darjun", 30)
  fmt.Println(t.Render())
}

run:

$ go run main.go
+--------+-----+
| User   | Age |
+--------+-----+
| dj     | 18  |
| darjun | 30  |
+--------+-----+

It is very convenient to use. First, call termtables.CreateTable() create a table object, call the object's AddHeader() method to add header information, and then call AddRow() add data row by row. Finally, call Render() to return the rendered table string.

mode

To deal with ordinary text tables, termtables also supports the output of HTML and Markdown format tables. Just call the SetModeHTML()/SetModeMarkdown() method of the table object to set some modes.

func main() {
  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())
}

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  |

The output format can be directly used in Markdown/HTML files.

to sum up

Relax today and learn about a small tool library termtables . Although it is not complicated to implement a similar one by yourself, the termtables library additionally helps us deal with more cumbersome details such as encoding and word width. If you need to print data like tables in the sample program, try termtables .

If you find a fun and useful Go language library, welcome to submit an issue on the Go Daily Library GitHub😄

reference

  1. Go a library GitHub every day: https://github.com/darjun/go-daily-lib
  2. termtables GitHub:github.com/scylladb/termtables

I

My blog: https://darjun.github.io

Welcome to follow my WeChat public account [GoUpUp], learn together and make progress together~


darjun
2.9k 声望359 粉丝