stable

package module
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2024 License: MIT Imports: 9 Imported by: 1

README

Go Report Card License GoDoc

Welcome to Simple Table (stable)

What is 'stable'?

stable can create ascii table from;

  • structs
  • struct arrays
  • json encoded byte arrays
  • string interface maps
  • string interface map arrays
  • csv encoded strings
  • custom row by row values

Functionalities

  • wide range of type support
  • value and header orientation options
  • custom print format option
  • char limiting
  • customizable border styles
  • and much more...

Examples

There are a lots of examples in Godoc page and example_test.go file.

Try your self!

anonymous struct array example:

	// any struct/struct array
	persons := []struct {
		Name      string
		Age       int
		Height    float64
		Available bool
	}{
		{Name: "Ruby Cohen", Age: 30, Height: 1.80, Available: true},
		{Name: "Bethany Parsons", Age: 29, Height: 1.58, Available: false},
		{Name: "Ronnie Rodriguez", Age: 28, Height: 1.78, Available: true},
		{Name: "Rosa Daniels", Age: 31, Height: 1.80, Available: true},
	}

	// convert it to table
	t, err := stable.ToTable(persons)
	if err != nil {
		fmt.Println(err)
		return
	}

	// set the table caption
	t.SetCaption("Customers")

	// print the table
	fmt.Println(t)

// output: 
// +-----------------------------------------------------+
// |                      Customers                      |
// |-----------------------------------------------------|
// |        Name        |  Age  |  Height  |  Available  |
// |--------------------+-------+----------+-------------|
// |  Ruby Cohen        |  30   |  1.8     |  true       |
// |  Bethany Parsons   |  29   |  1.58    |  false      |
// |  Ronnie Rodriguez  |  28   |  1.78    |  true       |
// |  Rosa Daniels      |  31   |  1.8     |  true       |
// +--------------------+-------+----------+-------------+

Create custom tables!

// create a table with caption
table := stable.New("Benchmark of Hashing")

// add fields
table.AddFields(
	"File",
	"File (KB)",
	"Chunk (KB)",
	"Time (ms)",
)

// add a field with more option
table.AddFieldWithOptions("Prop (%)", &stable.Options{
	Format:         "%0.2f",
	Alignment: stable.AlignmentCenter,
})

// add row
table.Row("/var/log/sys/crontab.log", 12.515, 14.265, "32", 0.223)
table.Row("/var/log/sys/monit.log", 85.521, 43.32, nil, 0.742)
table.Row("/var/log/sys/logrotate.log", 96.57, nil, "31112", 0.321)
table.Row("/var/log/sys/docker-daemon.log", 13.3511, 34.01, "3652", 0.895)

// print the table
fmt.Println(table)
// output:
// +------------------------------------------------------------------------------------------+
// |                                   Benchmark of Hashing                                   |
// |------------------------------------------------------------------------------------------|
// |               File               |  File (KB)  |  Chunk (KB)  |  Time (ms)  |  Prop (%)  |
// |----------------------------------+-------------+--------------+-------------+------------|
// |  /var/log/sys/crontab.log        |  12.515     |  14.265      |  32         |    0.22    |
// |  /var/log/sys/monit.log          |  85.521     |  43.32       |  -          |    0.74    |
// |  /var/log/sys/logrotate.log      |  96.57      |  -           |  31112      |    0.32    |
// |  /var/log/sys/docker-daemon.log  |  13.3511    |  34.01       |  3652       |    0.90    |
// +----------------------------------+-------------+--------------+-------------+------------+

Whats Next?

  • custom border style

Kudos

Documentation

Overview

Stable can create ascii table from;

  • structs (struct)
  • struct arrays ([]string)
  • json encoded byte arrays ([]byte)
  • string interface maps (map[string]interface{})
  • string interface map arrays ([]map[string]interface{})
  • csv encoded strings (string)
  • custom row by row values (.Row(values...interface{}))

Functionalities:

  • wide range of type support
  • value and header orientation options
  • custom print format option
  • char limiting
  • customizable border styles
  • and much more...

Index

Examples

Constants

View Source
const (
	// DefaultGeneralPadding default general padding of table
	DefaultGeneralPadding int = 2

	// MaxCaptionLength max caption length
	// if its greater than this constant it will trim the end with "..."
	MaxCaptionLength int = 50

	// MaxGeneralPadding maximum general padding
	MaxGeneralPadding int = 8
)
View Source
const (
	// AlignmentLeft alignment type left
	AlignmentLeft alignment = "left"
	// AlignmentCenter alignment type center
	AlignmentCenter alignment = "center"
	// AlignmentRight alignment type right
	AlignmentRight alignment = "right"
	// DefaultValueAlignment default value alignment type
	DefaultValueAlignment alignment = AlignmentLeft
	// DefaultHeaderAlignment default header alignment type
	DefaultHeaderAlignment alignment = AlignmentCenter
)
View Source
const (
	// NilValueString if a value is nil prints this
	NilValueString string = "-"
	// FieldIsNil if field pointer is nil return this line
	FieldIsNil string = "field is nil."
)
View Source
const (
	// BorderStyleDoubleLine double stripped border style
	BorderStyleDoubleLine borderStyleName = 1

	// BorderStyleSingleLine single stripped border style
	BorderStyleSingleLine borderStyleName = 2

	// BorderStylePrintableLine printable border style
	BorderStylePrintableLine borderStyleName = 3
)
View Source
const (
	// Version current version
	Version string = "v1.0.3"
)

Variables

View Source
var (
	// ErrNoField no field errors
	ErrNoField error = errors.New("'stable' error. there is no field on this table")

	// ErrNoRow no row error
	ErrNoRow error = errors.New("'stable' error. no row to show")
)
View Source
var (
	// ErrMalformedCSV malformed csv
	ErrMalformedCSV error = errors.New("'stable' error. malformed csv")
)
View Source
var (
	// ErrNotSupported error not supported type for convert to table
	ErrNotSupported error = errors.New("stable error. Type not supported")
)
View Source
var (
	// ErrNullJSON error null json
	ErrNullJSON error = errors.New("'stable' error. null json")
)

Functions

func Print added in v1.0.1

func Print(i interface{})

Print print the given type as table

Example
// example struct
type Person struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}

// lets create a bunch of person
persons := []*Person{
	{Name: "Ruby Cohen", Age: 30, Height: 1.80, Male: true},
	{Name: "Bethany Parsons", Age: 29, Height: 1.58},
	{Name: "Ronnie Rodriguez", Age: 28, Height: 1.78, Male: true},
	{Name: "Rosa Daniels", Age: 31, Height: 1.80, Male: true},
}

Print(persons)
Output:

+-------------------------------------------------+
|  age  |  height  |        name        |   male  |
|-------+----------+--------------------+---------|
|  30   |  1.8     |  Ruby Cohen        |  true   |
|  29   |  1.58    |  Bethany Parsons   |  false  |
|  28   |  1.78    |  Ronnie Rodriguez  |  true   |
|  31   |  1.8     |  Rosa Daniels      |  true   |
+-------+----------+--------------------+---------+

func PrintWithCaption added in v1.0.1

func PrintWithCaption(caption string, i interface{})

PrintWithCaption print the given type as table with caption

Example
// example struct
type Person struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}

// lets create a bunch of person
persons := []*Person{
	{Name: "Ruby Cohen", Age: 30, Height: 1.80, Male: true},
	{Name: "Bethany Parsons", Age: 29, Height: 1.58},
	{Name: "Ronnie Rodriguez", Age: 28, Height: 1.78, Male: true},
	{Name: "Rosa Daniels", Age: 31, Height: 1.80, Male: true},
}

PrintWithCaption("Customers of Coffee Shop", persons)
Output:

+-------------------------------------------------+
|             Customers of Coffee Shop            |
|-------------------------------------------------|
|  age  |  height  |        name        |   male  |
|-------+----------+--------------------+---------|
|  30   |  1.8     |  Ruby Cohen        |  true   |
|  29   |  1.58    |  Bethany Parsons   |  false  |
|  28   |  1.78    |  Ronnie Rodriguez  |  true   |
|  31   |  1.8     |  Rosa Daniels      |  true   |
+-------+----------+--------------------+---------+

func PrintWithScheme added in v1.0.3

func PrintWithScheme(sc *Scheme, i interface{}) error

PrintWithScheme print table with given table scheme and input

Example
// example struct
type Person struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}

// lets create a person named 'ruby'
ruby := &Person{
	Name:   "Ruby Cohen",
	Age:    31,
	Height: 1.853,
	Male:   true,
}

sc := &Scheme{
	Caption:        "Ruby Cohen Personal Info",
	GeneralPadding: 2,
	FieldOptions: map[string]*Options{
		"male":   {Hide: true},
		"height": {Format: "%0.2f m"},
	},
}
// print the ruby's info
PrintWithScheme(sc, ruby)

// if anything change
ruby.Age = 32

// we can print with same scheme
PrintWithScheme(sc, ruby)
Output:

+---------------------------------+
|     Ruby Cohen Personal Info    |
|---------------------------------|
|  age  |  height  |     name     |
|-------+----------+--------------|
|  31   |  1.85 m  |  Ruby Cohen  |
+-------+----------+--------------+

+---------------------------------+
|     Ruby Cohen Personal Info    |
|---------------------------------|
|  age  |  height  |     name     |
|-------+----------+--------------|
|  32   |  1.85 m  |  Ruby Cohen  |
+-------+----------+--------------+

Types

type BorderStyle

type BorderStyle struct {
	// contains filtered or unexported fields
}

BorderStyle border style main strcut

var (

	// DefaultLineStyle default line style
	DefaultLineStyle *BorderStyle = printableLine
)

type Field

type Field struct {
	// contains filtered or unexported fields
}

Field object every field object is a column

func NewFieldWithOptions

func NewFieldWithOptions(name string, opts *Options) *Field

NewFieldWithOptions create new field with options (alignment, char limit, format etc.)

func (*Field) AlignCenter

func (f *Field) AlignCenter()

AlignCenter align field values to center

func (*Field) AlignLeft

func (f *Field) AlignLeft()

AlignLeft align field values to left

func (*Field) AlignRight

func (f *Field) AlignRight()

AlignRight align field values to right

func (*Field) ChangeVisibility

func (f *Field) ChangeVisibility(hide bool)

ChangeVisibility change visibility of field ( hide | show )

func (*Field) GetAlignment

func (f *Field) GetAlignment() string

GetAlignment get value alignment ( left | center | right )

func (*Field) GetName

func (f *Field) GetName() string

GetName get fields name

func (*Field) Hide

func (f *Field) Hide()

Hide change visibility of field to 'hide'

Example
t := time.Date(2022, 01, 17, 0, 0, 0, 0, time.UTC)
user := []map[string]interface{}{
	{
		"username":   "ecoshub",
		"password":   "9b03c12b-ca05-4654-927a-56feb23cb8b3",
		"last_login": t.UnixNano(),
		"region":     "mena",
		"status":     1,
	},
	{
		"username":   "jenkins99",
		"password":   "981c8036-f017-4b15-920c-4b0c73948cf4",
		"last_login": t.UnixNano(),
		"region":     "mena",
		"status":     1,
	},
}

// convert struct array to table
table, err := ToTable(user)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Print(table)

// lets hie some fields (status, region)
table.GetFieldByName("status").Hide()
table.GetFieldByName("region").Hide()

// lets print the table again
fmt.Print(table)
Output:

+----------------------------------------------------------------------------------------------------+
|                                              user info                                             |
|----------------------------------------------------------------------------------------------------|
|       last_login      |                password                |  region  |  status  |   username  |
|-----------------------+----------------------------------------+----------+----------+-------------|
|  1642377600000000000  |  9b03c12b-ca05-4654-927a-56feb23cb8b3  |  mena    |  1       |  ecoshub    |
|  1642377600000000000  |  981c8036-f017-4b15-920c-4b0c73948cf4  |  mena    |  1       |  jenkins99  |
+-----------------------+----------------------------------------+----------+----------+-------------+
+------------------------------------------------------------------------------+
|                                   user info                                  |
|------------------------------------------------------------------------------|
|       last_login      |                password                |   username  |
|-----------------------+----------------------------------------+-------------|
|  1642377600000000000  |  9b03c12b-ca05-4654-927a-56feb23cb8b3  |  ecoshub    |
|  1642377600000000000  |  981c8036-f017-4b15-920c-4b0c73948cf4  |  jenkins99  |
+-----------------------+----------------------------------------+-------------+

func (*Field) IsHidden

func (f *Field) IsHidden() bool

IsHidden get visibility of field

func (*Field) SetAlignment

func (f *Field) SetAlignment(alignment alignment)

SetAlignment set a new alignment for field values.

Example
// create a table
table := New("table caption")

// add some field
table.AddFields("file", "size", "mod")

// change alignment of second and third field
table.GetField(1).AlignRight()
// another way
table.GetField(2).SetAlignment(AlignmentRight)

// lets add some value
table.Row("/var/log/docker", 12.453, 0777)

// print the table
fmt.Println(table)
Output:

+--------------------------------------+
|             table caption            |
|--------------------------------------|
|        file       |   size   |  mod  |
|-------------------+----------+-------|
|  /var/log/docker  |  12.453  |  511  |
+-------------------+----------+-------+

func (*Field) SetHeaderAlignment

func (f *Field) SetHeaderAlignment(alignment alignment)

SetHeaderAlignment SetHeaderAlignment.

func (*Field) SetName

func (f *Field) SetName(name string)

SetName set field a new name

func (*Field) SetOptions

func (f *Field) SetOptions(opts *Options)

SetOptions set field option.

Example
// create a table
table := New("table caption")

// add some field
table.AddFields("file", "size", "mod")

// change 'size' fields format option
table.GetFieldByName("size").SetOptions(&Options{
	Format:    "%0.1f (KB)",
	Alignment: AlignmentCenter,
})

table.Row("/var/log/docker", 12.453, 0777)

fmt.Println(table)
Output:

+-----------------------------------------+
|              table caption              |
|-----------------------------------------|
|        file       |     size    |  mod  |
|-------------------+-------------+-------|
|  /var/log/docker  |  12.5 (KB)  |  511  |
+-------------------+-------------+-------+

func (*Field) Show

func (f *Field) Show()

Show change visibility of field to 'show'

type Options

type Options struct {
	// print format of field
	// standart print format abbreviations are valid
	// example: (value 12.34)
	//     Fortmat: "%0.2f (ms)"
	// output: 12.34 (ms)
	Format string

	// alignment of value ( AlignmentCLeft | AlignmentCenter | AlignmentRight )
	// example:
	//     Alignment: AlignmentCenter
	Alignment alignment

	// alignment of field header ( AlignmentCLeft | AlignmentCenter | AlignmentRight )
	// example:
	//     Alignment: AlignmentRight
	HeaderAlignment alignment

	// hide | show the field
	Hide bool

	// limit the char output of value
	// example: (value: "/var/log/sys/crontab.log")
	//     CharLimit: 12
	// output: " /var/log/sys..."
	CharLimit int

	// char limit orientation
	// example: (value: "/var/log/sys/crontab.log")
	//     CharLimit: 12
	//     LimitFromStart: true
	// output: ".../crontab.log"
	LimitFromStart bool
}

Options field options

type STable

type STable struct {
	// contains filtered or unexported fields
}

STable simple table main struct

func Basic

func Basic(caption string, fieldNames ...string) *STable

Basic creates basic table with field names

Example
// create a basic table
table := Basic("caption of basic table", "brand", "quality", "year", "in_stock")

// add some rows
table.Row("asus", 10, 2016, true)
table.Row("apple", 8, 2020, true)
table.Row("samsung", 21, 2022, true)
table.Row("hp", 51, 2018, false)

fmt.Println(table)
Output:

+---------------------------------------------+
|            caption of basic table           |
|---------------------------------------------|
|   brand   |  quality  |  year  |  in_stock  |
|-----------+-----------+--------+------------|
|  asus     |  10       |  2016  |  true      |
|  apple    |  8        |  2020  |  true      |
|  samsung  |  21       |  2022  |  true      |
|  hp       |  51       |  2018  |  false     |
+-----------+-----------+--------+------------+

func CSVToTable

func CSVToTable(data string) (*STable, error)

CSVToTable convert csv encoded string to *STable

Example
c := `id,firstname,lastname,email,email2,profession
100,Nikki,Haldas,Nikki.Haldas@yopmail.com,Nikki.Haldas@gmail.com,worker
101,Blinni,Arquit,Blinni.Arquit@yopmail.com,Blinni.Arquit@gmail.com,doctor
102,Shandie,Douglass,Shandie.Douglass@yopmail.com,Shandie.Douglass@gmail.com,firefighter
103,Elie,Phaidra,Elie.Phaidra@yopmail.com,Elie.Phaidra@gmail.com,doctor
104,Jessy,Bahr,Jessy.Bahr@yopmail.com,Jessy.Bahr@gmail.com,police officer
105,Kalina,Hillel,Kalina.Hillel@yopmail.com,Kalina.Hillel@gmail.com,worker
106,Mathilda,Ambrosia,Mathilda.Ambrosia@yopmail.com,Mathilda.Ambrosia@gmail.com,police officer
107,Albertina,Klotz,Albertina.Klotz@yopmail.com,Albertina.Klotz@gmail.com,developer
108,Joeann,Lunsford,Joeann.Lunsford@yopmail.com,Joeann.Lunsford@gmail.com,firefighter
109,Roberta,Moseley,Roberta.Moseley@yopmail.com,Roberta.Moseley@gmail.com,worker
110,Eadie,Riva,Eadie.Riva@yopmail.com,Eadie.Riva@gmail.com,developer
111,Emelina,Keelia,Emelina.Keelia@yopmail.com,Emelina.Keelia@gmail.com,developer
112,Luci,McNully,Luci.McNully@yopmail.com,Luci.McNully@gmail.com,firefighter
113,Aurore,Franza,Aurore.Franza@yopmail.com,Aurore.Franza@gmail.com,doctor
1099,Cissiee,Trey,Cissiee.Trey@yopmail.com,Cissiee.Trey@gmail.com,developer`

// convert struct array to table
table, err := CSVToTable(c)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Println(table)
Output:

+------------------------------------------------------------------------------------------------------------------------+
|                                                        user info                                                       |
|------------------------------------------------------------------------------------------------------------------------|
|   id   |  firstname  |  lastname  |              email              |             email2            |    profession    |
|--------+-------------+------------+---------------------------------+-------------------------------+------------------|
|  100   |  Nikki      |  Haldas    |  Nikki.Haldas@yopmail.com       |  Nikki.Haldas@gmail.com       |  worker          |
|  101   |  Blinni     |  Arquit    |  Blinni.Arquit@yopmail.com      |  Blinni.Arquit@gmail.com      |  doctor          |
|  102   |  Shandie    |  Douglass  |  Shandie.Douglass@yopmail.com   |  Shandie.Douglass@gmail.com   |  firefighter     |
|  103   |  Elie       |  Phaidra   |  Elie.Phaidra@yopmail.com       |  Elie.Phaidra@gmail.com       |  doctor          |
|  104   |  Jessy      |  Bahr      |  Jessy.Bahr@yopmail.com         |  Jessy.Bahr@gmail.com         |  police officer  |
|  105   |  Kalina     |  Hillel    |  Kalina.Hillel@yopmail.com      |  Kalina.Hillel@gmail.com      |  worker          |
|  106   |  Mathilda   |  Ambrosia  |  Mathilda.Ambrosia@yopmail.com  |  Mathilda.Ambrosia@gmail.com  |  police officer  |
|  107   |  Albertina  |  Klotz     |  Albertina.Klotz@yopmail.com    |  Albertina.Klotz@gmail.com    |  developer       |
|  108   |  Joeann     |  Lunsford  |  Joeann.Lunsford@yopmail.com    |  Joeann.Lunsford@gmail.com    |  firefighter     |
|  109   |  Roberta    |  Moseley   |  Roberta.Moseley@yopmail.com    |  Roberta.Moseley@gmail.com    |  worker          |
|  110   |  Eadie      |  Riva      |  Eadie.Riva@yopmail.com         |  Eadie.Riva@gmail.com         |  developer       |
|  111   |  Emelina    |  Keelia    |  Emelina.Keelia@yopmail.com     |  Emelina.Keelia@gmail.com     |  developer       |
|  112   |  Luci       |  McNully   |  Luci.McNully@yopmail.com       |  Luci.McNully@gmail.com       |  firefighter     |
|  113   |  Aurore     |  Franza    |  Aurore.Franza@yopmail.com      |  Aurore.Franza@gmail.com      |  doctor          |
|  1099  |  Cissiee    |  Trey      |  Cissiee.Trey@yopmail.com       |  Cissiee.Trey@gmail.com       |  developer       |
+--------+-------------+------------+---------------------------------+-------------------------------+------------------+

func InjectScheme added in v1.0.3

func InjectScheme(sc *Scheme, i interface{}) (*STable, error)

InjectScheme inject a scheme to input to create a table with scheme

Example
// example struct
type Person struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}

// lets create a person named 'ruby'
ruby := &Person{
	Name:   "Ruby Cohen",
	Age:    31,
	Height: 1.853,
	Male:   true,
}

sc := &Scheme{
	Caption:        "Ruby Cohen Personal Info",
	GeneralPadding: 2,
	FieldOptions: map[string]*Options{
		"male":   {Hide: true},
		"height": {Format: "%0.2f m"},
	},
}

t, err := InjectScheme(sc, ruby)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(t)
Output:

+---------------------------------+
|     Ruby Cohen Personal Info    |
|---------------------------------|
|  age  |  height  |     name     |
|-------+----------+--------------|
|  31   |  1.85 m  |  Ruby Cohen  |
+-------+----------+--------------+

func New

func New(caption string) *STable

New new table, first param is table caption if given

Example
// create a table
table := New("table caption")

// add some field
table.AddFields("file", "size", "mod")

// lets add some value
table.Row("/var/log/docker", 12.453, 0777)

// print the table
fmt.Println(table)
Output:

+--------------------------------------+
|             table caption            |
|--------------------------------------|
|        file       |   size   |  mod  |
|-------------------+----------+-------|
|  /var/log/docker  |  12.453  |  511  |
+-------------------+----------+-------+

func ToTable

func ToTable(i interface{}) (*STable, error)

ToTable coverts other data types to *STable type

Example (AnonymousStruct)
// lets create an anonymous struct for purpose of example
// we can change field tag with 'table' keyword
fileInfo := struct {
	FilePath string  `table:"path"`
	FileSize float64 `table:"size"`
	FileMod  int     `table:"mod"`
}{
	FilePath: "/var/log/system.d/docker.log",
	FileSize: 1.8,
	FileMod:  0777,
}

// convert struct to table
table, err := ToTable(fileInfo)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("docker log file info")

// lets print 'mod' as octal for more
table.GetFieldByName("mod").SetOptions(&Options{
	Format: "%o",
})

// print the table
fmt.Println(table)
Output:

+-------------------------------------------------+
|               docker log file info              |
|-------------------------------------------------|
|              path              |  size  |  mod  |
|--------------------------------+--------+-------|
|  /var/log/system.d/docker.log  |  1.8   |  777  |
+--------------------------------+--------+-------+
Example (AnonymousStructArray)
persons := []*struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}{
	{Name: "Ruby Cohen", Age: 30, Height: 1.80, Male: true},
	{Name: "Bethany Parsons", Age: 29, Height: 1.58},
	{Name: "Ronnie Rodriguez", Age: 28, Height: 1.78, Male: true},
	{Name: "Rosa Daniels", Age: 31, Height: 1.80, Male: true},
}

// convert struct array to table
table, err := ToTable(persons)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("Customers of Coffee Shop")

// print the table
fmt.Println(table)
Output:

+-------------------------------------------------+
|             Customers of Coffee Shop            |
|-------------------------------------------------|
|  age  |  height  |        name        |   male  |
|-------+----------+--------------------+---------|
|  30   |  1.8     |  Ruby Cohen        |  true   |
|  29   |  1.58    |  Bethany Parsons   |  false  |
|  28   |  1.78    |  Ronnie Rodriguez  |  true   |
|  31   |  1.8     |  Rosa Daniels      |  true   |
+-------+----------+--------------------+---------+
Example (Json)
// example byte array ( json encoded )
j := []byte(`{"index": 1,"guid": "22c5c5c7-e3b8-40ec-9a83-450bc28c81df","isActive": true,"balance": "$2,057.64","picture": "http://placehold.it/32x32","age": 27}`)

// convert struct array to table
table, err := ToTable(j)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Println(table)
Output:

+-----------------------------------------------------+
|                      user info                      |
|-----------------------------------------------------|
|     key    |                  value                 |
|------------+----------------------------------------|
|  age       |  27                                    |
|  balance   |  $2,057.64                             |
|  guid      |  22c5c5c7-e3b8-40ec-9a83-450bc28c81df  |
|  index     |  1                                     |
|  isActive  |  true                                  |
|  picture   |  http://placehold.it/32x32             |
+------------+----------------------------------------+
Example (JsonArray)
// example byte array ( json encoded )
j := []byte(`[{"id": 0,"name": "Heath Vazquez", "age":40, "ssn":"6259d81d221425d39b2b02f5"},{"id": 1,"name": "Blanca Massey", "age":42, "ssn":"6259d8824e829833afacc3c7"},{"id": 2,"name": "Veronica Glass", "age":43, "ssn":"6259d8904d92bf035847e32a"}]`)

// convert struct array to table
table, err := ToTable(j)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Println(table)
Output:

+--------------------------------------------------------------+
|                           user info                          |
|--------------------------------------------------------------|
|  age  |  id  |       name       |             ssn            |
|-------+------+------------------+----------------------------|
|  40   |  0   |  Heath Vazquez   |  6259d81d221425d39b2b02f5  |
|  42   |  1   |  Blanca Massey   |  6259d8824e829833afacc3c7  |
|  43   |  2   |  Veronica Glass  |  6259d8904d92bf035847e32a  |
+-------+------+------------------+----------------------------+
Example (JsonArrayString)
// example byte array ( json encoded )
j := `[{"id": 0,"name": "Heath Vazquez", "age":40, "ssn":"6259d81d221425d39b2b02f5"},{"id": 1,"name": "Blanca Massey", "age":42, "ssn":"6259d8824e829833afacc3c7"},{"id": 2,"name": "Veronica Glass", "age":43, "ssn":"6259d8904d92bf035847e32a"}]`

// convert struct array to table
table, err := ToTable(j)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Println(table)
Output:

+--------------------------------------------------------------+
|                           user info                          |
|--------------------------------------------------------------|
|  age  |  id  |       name       |             ssn            |
|-------+------+------------------+----------------------------|
|  40   |  0   |  Heath Vazquez   |  6259d81d221425d39b2b02f5  |
|  42   |  1   |  Blanca Massey   |  6259d8824e829833afacc3c7  |
|  43   |  2   |  Veronica Glass  |  6259d8904d92bf035847e32a  |
+-------+------+------------------+----------------------------+
Example (Map)
t := time.Date(2022, 01, 17, 0, 0, 0, 0, time.UTC)
user := map[string]interface{}{
	"username":   "ecoshub",
	"password":   "9b03c12b-ca05-4654-927a-56feb23cb8b3",
	"last_login": t.UnixNano(),
	"region":     "mena",
	"status":     1,
}

// convert struct array to table
table, err := ToTable(user)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Println(table)
Output:

+-------------------------------------------------------+
|                       user info                       |
|-------------------------------------------------------|
|      key     |                  value                 |
|--------------+----------------------------------------|
|  last_login  |  1642377600000000000                   |
|  password    |  9b03c12b-ca05-4654-927a-56feb23cb8b3  |
|  region      |  mena                                  |
|  status      |  1                                     |
|  username    |  ecoshub                               |
+--------------+----------------------------------------+
Example (MapArray)
t := time.Date(2022, 01, 17, 0, 0, 0, 0, time.UTC)
user := []map[string]interface{}{
	{
		"username":   "ecoshub",
		"password":   "9b03c12b-ca05-4654-927a-56feb23cb8b3",
		"last_login": t.UnixNano(),
		"region":     "mena",
		"status":     1,
	},
	{
		"username":   "jenkins99",
		"password":   "981c8036-f017-4b15-920c-4b0c73948cf4",
		"last_login": t.UnixNano(),
		"region":     "mena",
		"status":     1,
	},
}

// convert struct array to table
table, err := ToTable(user)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("user info")

// print the table
fmt.Println(table)
Output:

+----------------------------------------------------------------------------------------------------+
|                                              user info                                             |
|----------------------------------------------------------------------------------------------------|
|       last_login      |                password                |  region  |  status  |   username  |
|-----------------------+----------------------------------------+----------+----------+-------------|
|  1642377600000000000  |  9b03c12b-ca05-4654-927a-56feb23cb8b3  |  mena    |  1       |  ecoshub    |
|  1642377600000000000  |  981c8036-f017-4b15-920c-4b0c73948cf4  |  mena    |  1       |  jenkins99  |
+-----------------------+----------------------------------------+----------+----------+-------------+
Example (Struct)
// example struct
type Person struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}

// lets create a person named 'ruby'
ruby := &Person{
	Name:   "Ruby Cohen",
	Age:    31,
	Height: 1.8,
	Male:   true,
}

// convert struct to table
table, err := ToTable(ruby)
if err != nil {
	fmt.Println(err)
	return
}
// print the table
fmt.Println(table)
Output:

+------------------------------------------+
|                  Person                  |
|------------------------------------------|
|  age  |  height  |     name     |  male  |
|-------+----------+--------------+--------|
|  31   |  1.8     |  Ruby Cohen  |  true  |
+-------+----------+--------------+--------+
Example (StructArray)
// example struct
type Person struct {
	Age    int     `table:"age"`
	Height float64 `table:"height"`
	Name   string  `table:"name"`
	Male   bool    `table:"male"`
}

// lets create a bunch of person
persons := []*Person{
	{Name: "Ruby Cohen", Age: 30, Height: 1.80, Male: true},
	{Name: "Bethany Parsons", Age: 29, Height: 1.58},
	{Name: "Ronnie Rodriguez", Age: 28, Height: 1.78, Male: true},
	{Name: "Rosa Daniels", Age: 31, Height: 1.80, Male: true},
}

// convert struct array to table
table, err := ToTable(persons)
if err != nil {
	fmt.Println(err)
	return
}

// add a caption
table.SetCaption("Customers of Coffee Shop")

// print the table
fmt.Println(table)
Output:

+-------------------------------------------------+
|             Customers of Coffee Shop            |
|-------------------------------------------------|
|  age  |  height  |        name        |   male  |
|-------+----------+--------------------+---------|
|  30   |  1.8     |  Ruby Cohen        |  true   |
|  29   |  1.58    |  Bethany Parsons   |  false  |
|  28   |  1.78    |  Ronnie Rodriguez  |  true   |
|  31   |  1.8     |  Rosa Daniels      |  true   |
+-------+----------+--------------------+---------+

func (*STable) AddField

func (st *STable) AddField(name string)

AddField adds a field with name

func (*STable) AddFieldWithOptions

func (st *STable) AddFieldWithOptions(name string, opts *Options)

AddFieldWithOptions adds a field with options

func (*STable) AddFields

func (st *STable) AddFields(fieldNames ...string) *STable

AddFields add new fields with name

func (*STable) Caption

func (st *STable) Caption() string

Caption get caption of table

func (*STable) FieldCount added in v1.0.2

func (st *STable) FieldCount() int

FieldCount get field count of table

Example
fileInfo := struct {
	FilePath string  `table:"path"`
	FileSize float64 `table:"size"`
	FileMod  int     `table:"mod"`
}{
	FilePath: "/var/log/system.d/docker.log",
	FileSize: 1.8,
	FileMod:  0777,
}

// convert struct to table
table, err := ToTable(fileInfo)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(table.FieldCount())
Output:

3

func (*STable) GetField

func (st *STable) GetField(index int) *Field

GetField get field with field index

func (*STable) GetFieldByName

func (st *STable) GetFieldByName(name string) *Field

GetFieldByName get field by field name

func (*STable) GetGeneralPadding

func (st *STable) GetGeneralPadding() int

GetGeneralPadding get general table padding

func (*STable) Row

func (st *STable) Row(values ...interface{})

Row add a row

func (*STable) SetCaption

func (st *STable) SetCaption(caption string)

SetCaption set caption for table

func (*STable) SetGeneralPadding

func (st *STable) SetGeneralPadding(padding int)

SetGeneralPadding set general table padding

func (*STable) SetStyle

func (st *STable) SetStyle(styleName borderStyleName) error

SetStyle set border style (BorderStyleDoubleLine | BorderStyleSingleLine | BorderStylePrintableLine)

func (*STable) String

func (st *STable) String() string

String table to string

type Scheme added in v1.0.3

type Scheme struct {
	Caption         string
	BorderStyleName borderStyleName
	GeneralPadding  int
	FieldOptions    map[string]*Options
}

Scheme main table scheme struct

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL