structtable

package module
v0.0.0-...-629ae18 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 11 Imported by: 0

README

go-structtable

⚠️ DEPRECATED ⚠️

This package is deprecated and no longer maintained. Please use github.com/domonda/go-retable instead, which provides improved functionality, better performance, and active maintenance.


Read and write data-table formats as slices of Go structs

Overview

The go-structtable package provides a comprehensive solution for converting between Go struct slices and various table formats including CSV, Excel, HTML, and custom text formats. It offers both reading (parsing) and writing (rendering) capabilities with flexible column mapping and formatting options.

Key Features

  • Multiple Format Support: CSV, Excel (.xlsx), HTML, and custom text formats
  • Flexible Column Mapping: Map struct fields to table columns using tags or custom logic
  • Type-Safe Operations: Full reflection-based type handling with custom formatters
  • Reader Interface: Unified interface for reading tabular data into struct slices
  • Renderer Interface: Unified interface for rendering struct slices to various formats
  • Format Detection: Automatic detection of CSV format parameters
  • Data Modification: Built-in modifiers for cleaning and transforming data

Core Concepts

Column Mapping

The package uses ColumnMapper implementations to define how struct fields map to table columns:

  • ReflectColumnTitles: Uses struct tags and field names for column mapping
  • ColumnTitles: Simple slice-based column title mapping
  • NoColumnTitles: Renders data without column headers
Readers

Readers implement the Reader interface to parse tabular data into struct instances:

  • CSV Reader: Parses CSV files with format detection and data modification
  • Excel Reader: Reads Excel (.xlsx) files from specific sheets
  • Text Reader: Works with pre-parsed 2D string slices
Renderers

Renderers implement the Renderer interface to convert struct slices into various formats:

  • HTML Renderer: Generates HTML tables with custom styling
  • CSV Renderer: Creates CSV files with configurable delimiters and quoting
  • Excel Renderer: Produces Excel files with formatting and multiple sheets
  • Text Renderer: Base renderer for custom text-based formats

Quick Start

Reading CSV Data
package main

import (
    "fmt"
    "os"
    
    "github.com/domonda/go-structtable"
    "github.com/domonda/go-structtable/csv"
)

type Person struct {
    Name string `col:"Full Name"`
    Age  int    `col:"Age"`
    City string `col:"City"`
}

func main() {
    // Open CSV file
    file, err := os.Open("people.csv")
    if err != nil {
        panic(err)
    }
    defer file.Close()
    
    // Create CSV reader
    reader, err := csv.NewReader(file, csv.NewFormat(","), "\n", nil, []csv.ColumnMapping{
        {Index: 0, StructField: "Name"},
        {Index: 1, StructField: "Age"},
        {Index: 2, StructField: "City"},
    })
    if err != nil {
        panic(err)
    }
    
    // Read data into struct slice
    var people []Person
    headers, err := structtable.Read(reader, &people, 1) // Skip 1 header row
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Headers: %v\n", headers)
    fmt.Printf("People: %+v\n", people)
}
Rendering HTML Tables
package main

import (
    "os"
    
    "github.com/domonda/go-structtable"
    "github.com/domonda/go-structtable/htmltable"
)

type Product struct {
    Name  string  `col:"Product Name"`
    Price float64 `col:"Price"`
    Stock int     `col:"In Stock"`
}

func main() {
    products := []Product{
        {Name: "Laptop", Price: 999.99, Stock: 5},
        {Name: "Mouse", Price: 29.99, Stock: 50},
        {Name: "Keyboard", Price: 79.99, Stock: 25},
    }
    
    // Render to HTML
    err := htmltable.Render(os.Stdout, products, "Product Catalog", true, structtable.DefaultReflectColumnTitles)
    if err != nil {
        panic(err)
    }
}
Custom Column Mapping
package main

import (
    "fmt"
    "reflect"
    
    "github.com/domonda/go-structtable"
)

type User struct {
    ID       int    `col:"-"`           // Ignored
    Username string `col:"User Name"`    // Custom title
    Email    string                     // Uses SpacePascalCase: "Email"
    Active   bool   `col:"Is Active"`   // Custom title
}

func main() {
    users := []User{
        {ID: 1, Username: "john", Email: "[email protected]", Active: true},
        {ID: 2, Username: "jane", Email: "[email protected]", Active: false},
    }
    
    // Use default column mapper
    mapper := structtable.DefaultReflectColumnTitles
    
    // Get column titles and row reflector
    titles, reflector := mapper.ColumnTitlesAndRowReflector(reflect.TypeOf(User{}))
    fmt.Printf("Column titles: %v\n", titles)
    // Output: [User Name Email Is Active]
    
    // Reflect values from first user
    values := reflector.ReflectRow(reflect.ValueOf(users[0]))
    fmt.Printf("First user values: %v\n", values)
}

Package Structure

Main Package (structtable)
  • Interfaces: Reader, Renderer, ColumnMapper, RowReflector
  • Core Functions: Read, Render, RenderTo, RenderBytes, RenderFile
  • Column Mappers: ReflectColumnTitles, ColumnTitles, NoColumnTitles
  • Utilities: StructFieldTypes, StructFieldValues, SpacePascalCase
CSV Package (csv)
  • Reader: csv.Reader for parsing CSV files
  • Renderer: csv.Renderer for generating CSV files
  • Format: csv.Format and csv.FormatDetectionConfig
  • Modifiers: Data cleaning and transformation functions
  • Types: csv.DataType for type detection
Excel Package (excel)
  • Reader: excel.Reader for reading Excel files
  • Renderer: excel.Renderer for generating Excel files
  • Configuration: excel.ExcelFormatConfig for formatting options
  • Cell Writers: Custom formatting for different data types
HTML Package (htmltable)
  • Renderer: htmltable.Renderer for generating HTML tables
  • Configuration: structtable.HTMLTableConfig for styling options
Text Table Package (texttable)
  • Interface: texttable.Table for accessing tabular data
  • Implementation: texttable.StringsTable for 2D string slices
  • Utilities: texttable.BoundingBox for spatial information

Advanced Usage

Custom Format Renderer
type CustomRenderer struct {
    *structtable.TextRenderer
}

func (r *CustomRenderer) RenderBeginTableText(w io.Writer) error {
    _, err := fmt.Fprintf(w, "=== TABLE START ===\n")
    return err
}

func (r *CustomRenderer) RenderHeaderRowText(w io.Writer, titles []string) error {
    _, err := fmt.Fprintf(w, "HEADER: %s\n", strings.Join(titles, " | "))
    return err
}

func (r *CustomRenderer) RenderRowText(w io.Writer, fields []string) error {
    _, err := fmt.Fprintf(w, "ROW: %s\n", strings.Join(fields, " | "))
    return err
}

func (r *CustomRenderer) RenderEndTableText(w io.Writer) error {
    _, err := fmt.Fprintf(w, "=== TABLE END ===\n")
    return err
}
Data Modification
// Apply modifiers to clean CSV data
modifiers := csv.ModifierList{
    csv.RemoveEmptyRowsModifier{},
    csv.CompactSpacedStringsModifier{},
    csv.SetRowsWithNonUniformColumnsNilModifier{},
}

reader, err := csv.NewReader(file, format, "\n", modifiers, columnMappings)
Format Detection
// Automatically detect CSV format
config := csv.NewFormatDetectionConfig()
rows, format, err := csv.ParseDetectFormat(data, config)

Migration to go-retable

If you're currently using go-structtable, consider migrating to go-retable for:

  • Better performance and memory efficiency
  • More flexible column mapping options
  • Enhanced error handling and validation
  • Active maintenance and bug fixes
  • Additional format support
  • Improved API design

License

This package is part of the Domonda project and follows the same licensing terms.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultReflectColumnTitles = &ReflectColumnTitles{
	Tag:                "col",
	IgnoreTitle:        "-",
	UntaggedFieldTitle: SpacePascalCase,
}

DefaultReflectColumnTitles provides the default ReflectColumnTitles using "col" as Tag and the SpacePascalCase function for UntaggedFieldTitle. Implements ColumnMapper.

This is the recommended default configuration for mapping struct fields to column titles. It uses the "col" struct tag for explicit column names, "-" as the ignore marker, and SpacePascalCase for formatting untagged fields.

Example usage:

type Person struct {
    Name string `col:"Full Name"`
    Age  int    // Will be formatted as "Age"
    ID   string `col:"-"` // Will be ignored
}

Functions

func Read

func Read(reader Reader, structSlicePtr any, numHeaderRows int) (headerRows [][]string, err error)

Read reads table data from a Reader into a slice of structs.

This function reads all rows from the Reader and populates a slice of structs with the data. It can optionally skip header rows and return them separately.

Parameters:

  • reader: The Reader implementation to read data from
  • structSlicePtr: A pointer to a slice of structs to populate
  • numHeaderRows: Number of header rows to skip (returned separately)

Returns:

  • headerRows: The header rows that were skipped (if any)
  • err: Any error that occurred during reading

Example:

var people []Person
headers, err := Read(csvReader, &people, 1)

func Render

func Render(renderer Renderer, structSlice any, renderTitleRow bool, columnMapper ColumnMapper) error

Render renders a slice of structs into a table using the given Renderer.

This function takes a slice of structs and renders them as a table using the provided Renderer implementation. It uses the ColumnMapper to determine column titles and extract values from the struct instances.

Parameters:

  • renderer: The Renderer implementation to use for output formatting
  • structSlice: The slice of structs to render
  • renderTitleRow: Whether to include a header row with column titles
  • columnMapper: The ColumnMapper to use for field-to-column mapping

Returns:

  • err: Any error that occurred during rendering

func RenderBytes

func RenderBytes(renderer Renderer, structSlice any, renderTitleRow bool, columnMapper ColumnMapper) ([]byte, error)

RenderBytes renders a slice of structs into a table and returns the result as bytes.

This is a convenience function that combines Render and Result. It renders the struct slice and returns the result as a byte slice.

Parameters:

  • renderer: The Renderer implementation to use for output formatting
  • structSlice: The slice of structs to render
  • renderTitleRow: Whether to include a header row with column titles
  • columnMapper: The ColumnMapper to use for field-to-column mapping

Returns:

  • data: The rendered table data as bytes
  • err: Any error that occurred during rendering

func RenderFile

func RenderFile(file fs.File, renderer Renderer, structSlice any, renderTitleRow bool, columnMapper ColumnMapper) error

RenderFile renders a slice of structs into a table and writes the result to a file.

This is a convenience function that combines Render and WriteResultFile. It renders the struct slice and immediately writes the result to the provided file.

Parameters:

  • file: The fs.File to write the rendered table to
  • renderer: The Renderer implementation to use for output formatting
  • structSlice: The slice of structs to render
  • renderTitleRow: Whether to include a header row with column titles
  • columnMapper: The ColumnMapper to use for field-to-column mapping

Returns:

  • err: Any error that occurred during rendering or writing

func RenderTo

func RenderTo(writer io.Writer, renderer Renderer, structSlice any, renderTitleRow bool, columnMapper ColumnMapper) error

RenderTo renders a slice of structs into a table and writes the result to a writer.

This is a convenience function that combines Render and WriteResultTo. It renders the struct slice and immediately writes the result to the provided writer.

Parameters:

  • writer: The io.Writer to write the rendered table to
  • renderer: The Renderer implementation to use for output formatting
  • structSlice: The slice of structs to render
  • renderTitleRow: Whether to include a header row with column titles
  • columnMapper: The ColumnMapper to use for field-to-column mapping

Returns:

  • err: Any error that occurred during rendering or writing

func SpacePascalCase

func SpacePascalCase(name string) string

SpacePascalCase inserts spaces before upper case characters within PascalCase like names. It also replaces underscore '_' characters with spaces.

This function is commonly used as the UntaggedFieldTitle function for ReflectColumnTitles to create human-readable column names from struct field names.

Examples:

  • "FirstName" -> "First Name"
  • "UserID" -> "User ID"
  • "CreatedAt" -> "Created At"
  • "user_name" -> "user name"

Parameters:

  • name: The field name to format

Returns:

  • The formatted name with spaces inserted appropriately

func StructFieldTypes

func StructFieldTypes(structType reflect.Type) (fields []reflect.StructField)

StructFieldTypes returns the exported fields of a struct type including the inlined fields of any anonymously embedded structs.

This function recursively traverses a struct type and returns all exported fields, including those from embedded structs. It handles pointer types by dereferencing them to get the underlying struct type.

Parameters:

  • structType: The reflect.Type of the struct to analyze

Returns:

  • fields: Slice of reflect.StructField representing all exported fields

func StructFieldValues

func StructFieldValues(structValue reflect.Value) (values []reflect.Value)

StructFieldValues returns the reflect.Value of exported struct fields including the inlined fields of any anonymously embedded structs.

This function recursively traverses a struct value and returns all exported field values, including those from embedded structs. It handles pointer types by dereferencing them to get the underlying struct value.

Parameters:

  • structValue: The reflect.Value of the struct instance to analyze

Returns:

  • values: Slice of reflect.Value representing all exported field values

Types

type ColumnMapper

type ColumnMapper interface {
	// ColumnTitlesAndRowReflector returns the column titles and indices for structFields.
	// The length of the titles and indices slices must be identical to the length of structFields.
	// The indices start at zero, the special index -1 filters removes the column
	// for the corresponding struct field.
	//
	// Parameters:
	//   - structType: The reflect.Type of the struct to map
	//
	// Returns:
	//   - titles: Slice of column titles for the table header
	//   - rowReflector: RowReflector that can extract values from struct instances
	ColumnTitlesAndRowReflector(structType reflect.Type) (titles []string, rowReflector RowReflector)
}

ColumnMapper is used to map struct type fields to column names.

This interface defines how to extract column titles and create a RowReflector from a struct type. It's the core abstraction for converting struct types into table column definitions.

func NoColumnTitles

func NoColumnTitles() ColumnMapper

NoColumnTitles returns a ColumnMapper that returns nil as column titles and the StructFieldValues function of this package as RowReflector.

This is useful when you want to render table data without column headers, such as when generating data-only exports or when headers are handled separately.

type ColumnMapperFunc

type ColumnMapperFunc func(structType reflect.Type) (titles []string, rowReflector RowReflector)

ColumnMapperFunc implements the ColumnMapper interface with a function.

This allows you to use a simple function as a ColumnMapper without creating a custom type.

func (ColumnMapperFunc) ColumnTitlesAndRowReflector

func (f ColumnMapperFunc) ColumnTitlesAndRowReflector(structType reflect.Type) (titles []string, rowReflector RowReflector)

ColumnTitlesAndRowReflector calls the underlying function to map struct fields.

type ColumnTitles

type ColumnTitles []string

ColumnTitles implements ColumnMapper by returning the underlying string slice as column titles and the StructFieldValues function of this package as RowReflector.

This is a simple implementation that uses the provided string slice as column titles and maps them directly to struct fields in order. It does not check if the number of column titles and the reflected row values are identical, and re-mapping or ignoring of columns is not possible.

Use this when you have a fixed set of column titles that correspond directly to struct fields in order.

func (ColumnTitles) ColumnTitlesAndRowReflector

func (t ColumnTitles) ColumnTitlesAndRowReflector(structType reflect.Type) (titles []string, rowReflector RowReflector)

ColumnTitlesAndRowReflector returns the column titles and a RowReflector that uses StructFieldValues to extract values from struct instances.

type HTMLFormatRenderer

type HTMLFormatRenderer interface {
	// RenderBeforeTable is useful when you want to add custom styles or render anything before the table element.
	//
	// This method is called before the table element is rendered, allowing
	// you to add custom CSS styles, scripts, or other HTML content.
	RenderBeforeTable(writer io.Writer) error
}

HTMLFormatRenderer is the renderer for the HTML format.

This interface defines methods for customizing HTML table rendering, particularly for adding custom styles or content before the table element.

type HTMLRenderer

type HTMLRenderer struct {
	TableConfig *HTMLTableConfig
	// contains filtered or unexported fields
}

HTMLRenderer implements Renderer by using a HTMLFormatRenderer for a specific text based table format.

This renderer generates HTML tables from struct slices, with support for custom formatting, CSS classes, and pre-table content rendering.

func NewHTMLRenderer

func NewHTMLRenderer(format HTMLFormatRenderer, TableConfig *HTMLTableConfig, config *strfmt.FormatConfig) *HTMLRenderer

NewHTMLRenderer creates a new HTMLRenderer instance.

This constructor initializes an HTMLRenderer with the provided format renderer, table configuration, and text formatting configuration.

Parameters:

  • format: The HTMLFormatRenderer for custom pre-table content
  • TableConfig: Configuration for the HTML table appearance
  • config: Text formatting configuration for cell values

Returns:

  • A new HTMLRenderer instance ready for use

func (*HTMLRenderer) MIMEType

func (*HTMLRenderer) MIMEType() string

MIMEType returns the MIME-Type of the rendered content.

This method implements the Renderer interface and returns the MIME type for HTML content with UTF-8 encoding.

func (*HTMLRenderer) RenderHeaderRow

func (htm *HTMLRenderer) RenderHeaderRow(columnTitles []string) error

RenderHeaderRow renders the table header row with the given column titles.

This method implements the Renderer interface and generates the HTML for the table header row, including the opening table tag and caption.

func (*HTMLRenderer) RenderRow

func (htm *HTMLRenderer) RenderRow(columnValues []reflect.Value) error

RenderRow renders a single data row with the given column values.

This method implements the Renderer interface and generates the HTML for a single table row with the provided column values.

func (*HTMLRenderer) Result

func (htm *HTMLRenderer) Result() ([]byte, error)

Result returns the rendered table data as bytes.

This method implements the Renderer interface and returns the complete HTML table as a byte slice, including the closing table tag.

func (*HTMLRenderer) WriteResultFile

func (htm *HTMLRenderer) WriteResultFile(file fs.File, perm ...fs.Permissions) error

WriteResultFile writes the rendered table data to the given file.

This method implements the Renderer interface and writes the complete HTML table to the provided file with optional permissions.

func (*HTMLRenderer) WriteResultTo

func (htm *HTMLRenderer) WriteResultTo(writer io.Writer) error

WriteResultTo writes the rendered table data to the given writer.

This method implements the Renderer interface and writes the complete HTML table to the provided writer.

type HTMLTableConfig

type HTMLTableConfig struct {
	// Caption is the table caption text.
	Caption string
	// TableClass is the CSS class for the table element.
	TableClass string
	// CaptionClass is the CSS class for the caption element.
	CaptionClass string
	// RowClass is the CSS class applied to all table rows.
	RowClass string
	// CellClass is the CSS class applied to all table cells.
	CellClass string
	// HeaderRowClass is the CSS class for header rows.
	HeaderRowClass string
	// HeaderCellClass is the CSS class for header cells.
	HeaderCellClass string
	// DataRowClass is the CSS class for data rows.
	DataRowClass string
	// DataCellClass is the CSS class for data cells.
	DataCellClass string
}

HTMLTableConfig is the config for the actual, visual, resulting HTML table.

This struct contains configuration options for customizing the appearance and structure of the generated HTML table, including CSS classes and captions.

type Reader

type Reader interface {
	// NumRows returns the total number of rows available for reading.
	NumRows() int
	// ReadRowStrings returns the raw string values for a specific row.
	// This is useful for debugging or when you need access to the raw data.
	ReadRowStrings(index int) ([]string, error)
	// ReadRow populates a struct instance with data from the specified row.
	// The destStruct parameter should be a reflect.Value of the struct to populate.
	ReadRow(index int, destStruct reflect.Value) error
}

Reader defines the interface for reading table data into struct slices.

This interface provides methods to read tabular data and convert it into Go struct instances. It supports both string-based access and direct struct field population.

type ReflectColumnTitles

type ReflectColumnTitles struct {
	// Tag is the struct field tag to be used as column name.
	// If a field has this tag, its value will be used as the column title.
	Tag string
	// IgnoreTitle will result in a column index of -1.
	// Fields with this tag value will be excluded from the table.
	IgnoreTitle string
	// UntaggedFieldTitle will be called with the struct field name to
	// return a column name in case the struct field has no tag named Tag.
	// If UntaggedFieldTitle is nil, then the struct field name will be used unchanged.
	UntaggedFieldTitle func(fieldName string) (columnTitle string)
	// MapIndices is a map from the index of a field in struct
	// to the column index returned by ColumnTitlesAndRowReflector.
	// If MapIndices is nil, then no mapping will be performed.
	// Map to the index -1 to not create a column for a struct field.
	MapIndices map[int]int
}

ReflectColumnTitles implements ColumnMapper with a struct field Tag to be used for naming and a UntaggedFieldTitle in case the Tag is not set.

This is the most flexible and commonly used ColumnMapper implementation. It uses struct tags to determine column names and provides fallback formatting for untagged fields. It also supports field mapping and filtering through the MapIndices field.

Example usage:

type Person struct {
    Name string `col:"Full Name"`
    Age  int    // Will use UntaggedFieldTitle function
    ID   string `col:"-"` // Will be ignored
}

mapper := &ReflectColumnTitles{
    Tag: "col",
    IgnoreTitle: "-",
    UntaggedFieldTitle: SpacePascalCase,
}

func (*ReflectColumnTitles) ColumnTitlesAndRowReflector

func (n *ReflectColumnTitles) ColumnTitlesAndRowReflector(structType reflect.Type) (titles []string, rowReflector RowReflector)

ColumnTitlesAndRowReflector implements the ColumnMapper interface.

This method analyzes the struct type and returns column titles and a RowReflector based on the configuration of this ReflectColumnTitles instance. It handles struct tags, field mapping, and filtering according to the configured rules.

func (*ReflectColumnTitles) String

func (n *ReflectColumnTitles) String() string

String returns a string representation of the ReflectColumnTitles configuration.

This is useful for debugging and logging purposes to see the current tag and ignore title configuration.

func (*ReflectColumnTitles) WithIgnoreIndex

func (n *ReflectColumnTitles) WithIgnoreIndex(fieldIndex int) *ReflectColumnTitles

WithIgnoreIndex returns a copy of ReflectColumnTitles that ignores the specified field.

This method creates a new instance that will exclude the field at fieldIndex from the output table by mapping it to column index -1.

Parameters:

  • fieldIndex: The index of the struct field to ignore (0-based)

func (*ReflectColumnTitles) WithIgnoreTitle

func (n *ReflectColumnTitles) WithIgnoreTitle(ignoreTitle string) *ReflectColumnTitles

WithIgnoreTitle returns a copy of ReflectColumnTitles with the specified ignore title.

This method creates a new instance with the modified ignore title, allowing for fluent configuration of the ColumnMapper.

func (*ReflectColumnTitles) WithMapIndex

func (n *ReflectColumnTitles) WithMapIndex(fieldIndex, columnIndex int) *ReflectColumnTitles

WithMapIndex returns a copy of ReflectColumnTitles with a field-to-column mapping.

This method creates a new instance with an additional mapping from fieldIndex to columnIndex, allowing for reordering or filtering of columns.

Parameters:

  • fieldIndex: The index of the struct field (0-based)
  • columnIndex: The index of the column in the output table (0-based)

func (*ReflectColumnTitles) WithMapIndices

func (n *ReflectColumnTitles) WithMapIndices(mapIndices map[int]int) *ReflectColumnTitles

WithMapIndices returns a copy of ReflectColumnTitles with the specified field mappings.

This method creates a new instance with the complete map of field-to-column mappings, replacing any existing mappings.

Parameters:

  • mapIndices: Map from struct field indices to column indices

func (*ReflectColumnTitles) WithTag

WithTag returns a copy of ReflectColumnTitles with the specified tag.

This method creates a new instance with the modified tag, allowing for fluent configuration of the ColumnMapper.

type Renderer

type Renderer interface {
	// RenderHeaderRow renders the table header row with the given column titles.
	RenderHeaderRow(columnTitles []string) error
	// RenderRow renders a single data row with the given column values.
	RenderRow(columnValues []reflect.Value) error

	// Result returns the rendered table data as bytes.
	Result() ([]byte, error)
	// WriteResultTo writes the rendered table data to the given writer.
	WriteResultTo(w io.Writer) error
	// WriteResultFile writes the rendered table data to the given file.
	WriteResultFile(file fs.File, perm ...fs.Permissions) error

	// MIMEType returns the MIME-Type of the rendered content.
	MIMEType() string
}

Renderer defines the interface for rendering struct slices into various table formats.

This interface provides methods to render tabular data from Go struct slices into different output formats such as HTML, CSV, Excel, etc.

type RowReflector

type RowReflector interface {
	// ReflectRow returns reflection values for struct fields
	// of structValue representing a table row.
	//
	// The returned slice should contain reflect.Value objects for each
	// column in the same order as the column titles returned by
	// ColumnMapper.ColumnTitlesAndRowReflector.
	ReflectRow(structValue reflect.Value) (columnValues []reflect.Value)
}

RowReflector is used to reflect column values from the fields of a struct representing a table row.

This interface defines how to extract values from a struct instance and convert them into a slice of reflect.Value objects that can be used for rendering table rows.

type RowReflectorFunc

type RowReflectorFunc func(structValue reflect.Value) (columnValues []reflect.Value)

RowReflectorFunc implements RowReflector with a function.

This allows you to use a simple function as a RowReflector without creating a custom type.

func (RowReflectorFunc) ReflectRow

func (f RowReflectorFunc) ReflectRow(structValue reflect.Value) (columnValues []reflect.Value)

ReflectRow calls the underlying function to reflect row values.

type TextFormatRenderer

type TextFormatRenderer interface {
	// RenderBeginTableText renders any content that should appear before the table.
	RenderBeginTableText(writer io.Writer) error
	// RenderHeaderRowText renders a header row with the given column titles.
	RenderHeaderRowText(writer io.Writer, columnTitles []string) error
	// RenderRowText renders a data row with the given field values.
	RenderRowText(writer io.Writer, fields []string) error
	// RenderEndTableText renders any content that should appear after the table.
	RenderEndTableText(writer io.Writer) error
}

TextFormatRenderer has to be implemented for a format to be used by TextRenderer.

This interface defines methods for rendering text-based table formats, such as CSV, TSV, or custom delimited formats.

type TextReader

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

TextReader implements the Reader interface for reading tabular data from a 2D slice of strings into struct instances.

This reader is useful when you have pre-parsed tabular data as strings and want to populate struct instances with the data. It supports column mapping and custom scanning configuration.

func NewTextReader

func NewTextReader(rows [][]string, columnMapping map[int]string, columnTitleTag string, scanConfig ...*strfmt.ScanConfig) *TextReader

NewTextReader creates a new TextReader instance.

This constructor initializes a TextReader with the provided data and configuration. The columnMapping maps column indices to struct field names, and the columnTitleTag specifies which struct tag to use for field name resolution.

Parameters:

  • rows: The 2D slice of strings containing the tabular data
  • columnMapping: Map from column index to struct field name
  • columnTitleTag: The struct tag to use for field name resolution
  • scanConfig: Optional scanning configuration (uses default if nil)

Returns:

  • A new TextReader instance ready for use

func (*TextReader) NumRows

func (tr *TextReader) NumRows() int

NumRows returns the total number of rows available for reading.

This method implements the Reader interface and returns the count of rows in the underlying data.

func (*TextReader) ReadRow

func (tr *TextReader) ReadRow(index int, destStruct reflect.Value) error

ReadRow populates a struct instance with data from the specified row.

This method implements the Reader interface and populates the destStruct with data from the row at the given index. It uses the columnMapping to determine which columns correspond to which struct fields, and uses the columnTitleTag to resolve field names from struct tags.

Parameters:

  • index: The row index to read (0-based)
  • destStruct: The reflect.Value of the struct to populate

Returns:

  • err: Any error that occurred during reading or field population

type TextRenderer

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

TextRenderer implements Renderer by using a TextFormatRenderer for a specific text based table format.

This renderer generates text-based tables from struct slices, with support for custom formatting through the TextFormatRenderer interface.

func NewTextRenderer

func NewTextRenderer(format TextFormatRenderer, config *strfmt.FormatConfig) *TextRenderer

NewTextRenderer creates a new TextRenderer instance.

This constructor initializes a TextRenderer with the provided format renderer and text formatting configuration.

Parameters:

  • format: The TextFormatRenderer for custom text formatting
  • config: Text formatting configuration for cell values

Returns:

  • A new TextRenderer instance ready for use

func (*TextRenderer) RenderHeaderRow

func (txt *TextRenderer) RenderHeaderRow(columnTitles []string) error

RenderHeaderRow renders the table header row with the given column titles.

This method implements the Renderer interface and generates the text for the table header row, including any pre-table content.

func (*TextRenderer) RenderRow

func (txt *TextRenderer) RenderRow(columnValues []reflect.Value) error

RenderRow renders a single data row with the given column values.

This method implements the Renderer interface and generates the text for a single table row with the provided column values.

func (*TextRenderer) Result

func (txt *TextRenderer) Result() ([]byte, error)

Result returns the rendered table data as bytes.

This method implements the Renderer interface and returns the complete text table as a byte slice, including any post-table content.

func (*TextRenderer) WriteResultFile

func (txt *TextRenderer) WriteResultFile(file fs.File, perm ...fs.Permissions) error

WriteResultFile writes the rendered table data to the given file.

This method implements the Renderer interface and writes the complete text table to the provided file with optional permissions.

func (*TextRenderer) WriteResultTo

func (txt *TextRenderer) WriteResultTo(writer io.Writer) error

WriteResultTo writes the rendered table data to the given writer.

This method implements the Renderer interface and writes the complete text table to the provided writer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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