print tables in golang
cute cli with the standard library
The standard library has a hidden gem called text/tabwriter which can be used to pretty print a table in the CLI.
The parameters from this blogpost gives quite a pleasant result:
ID Track Title Disc Suffix Bitrate Duration Size Album ID
-- ----- ----- ---- ------ ------- -------- ---- --------
tr-2927 1 Østenfor Sol og vestenfor Maane 1 flac 736Kbps 3m26s 582MB al-463
tr-2928 2 Ord 1 flac 516Kbps 17s 972MB al-463
tr-2929 3 Høyfjeldsbilde 1 flac 631Kbps 2m15s 869MB al-463
tr-2930 4 Nattleite 1 flac 700Kbps 2m11s 516MB al-463
tr-2931 5 Kveldssang 1 flac 562Kbps 1m32s 282MB al-463
tr-2932 6 Naturmystikk 1 flac 640Kbps 2m55s 666MB al-463
tr-2933 7 A cappella (Sielens sang) 1 flac 665Kbps 1m26s 893MB al-463
tr-2934 8 Hiertets vee 1 flac 682Kbps 3m54s 128MB al-463
tr-2935 9 Kledt i nattens farger 1 flac 649Kbps 2m51s 522MB al-463
tr-2936 10 Halling 1 flac 633Kbps 2m7s 536MB al-463
tr-2937 11 Utreise 1 flac 676Kbps 2m56s 833MB al-463
tr-2938 12 Søfn‐ør paa Alfers Lund 1 flac 654Kbps 2m37s 438MB al-463
tr-2939 13 Ulvsblakk 1 flac 732Kbps 6m56s 368MB al-463
The “underlined” header can be added as follows1:
func SongsTable() string {
text := []string{}
// Header fields
header := []string{
"ID",
"Track",
"Title",
"Disc",
"Suffix",
"Bitrate",
"Duration",
"Size",
"Album ID"
}
// The "---" under each header
headerLine := []string{}
for _, i := range header {
headerLine = append(headerLine, strings.Repeat("-", len(i)))
}
text = append(
text,
[]string{strings.Join(header, "\t"),
strings.Join(headerLine, "\t")}...,
)
// The content of the table
content := []string{}
// ...
// (Append to `content` the rows of the table, with each field tab delimited)
// ...
text = append(text, content)
return strings.Join(text, "\n")
}
-
Code based on aquamarine. ↩︎