gnfmt

package module
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: MIT Imports: 11 Imported by: 49

README

gnfmt

Go Report Card GoDoc

gnfmt is a Go helper library designed to simplify data serialization and enhance command-line interface (CLI) output. It provides tools for converting Go data structures into various formats.

Features

  • Data Serialization: Convert Go objects to JSON (compact/pretty), CSV, TSV, and Gob formats
  • Pretty Printing: Display Go objects in a human-readable JSON format in the terminal
  • CSV/TSV Utilities: Read headers, convert records, and normalize row sizes
  • Time Formatting: Convert seconds into human-readable duration strings
  • Flexible Encoders: Pluggable encoder interface for easy format switching

Installation

go get github.com/gnames/gnfmt

Usage

Data Serialization and Formatting

gnfmt supports multiple output formats for your data structures.

Format Types
package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

func main() {
	// Create format from string
	format, err := gnfmt.NewFormat("pretty")
	if err != nil {
		panic(err)
	}

	fmt.Println(format) // Output: "pretty JSON"

	// Available formats:
	// - "csv"     -> CSV format
	// - "tsv"     -> TSV (tab-separated) format
	// - "compact" -> Compact JSON (single line)
	// - "pretty"  -> Pretty JSON (indented)
}
JSON Encoding
package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	person := Person{Name: "Alice", Age: 30}

	// Compact JSON
	encoder := gnfmt.GNjson{Pretty: false}
	data, _ := encoder.Encode(person)
	fmt.Println(string(data)) // {"name":"Alice","age":30}

	// Pretty JSON
	encoder.Pretty = true
	data, _ = encoder.Encode(person)
	fmt.Println(string(data))
	// {
	//   "name": "Alice",
	//   "age": 30
	// }

	// Quick pretty print
	fmt.Println(gnfmt.Ppr(person))
}
Gob Encoding
package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

func main() {
	data := map[string]int{"apples": 5, "oranges": 3}

	encoder := gnfmt.GNgob{}

	// Encode to gob
	gobData, err := encoder.Encode(data)
	if err != nil {
		panic(err)
	}

	// Decode from gob
	var result map[string]int
	err = encoder.Decode(gobData, &result)
	if err != nil {
		panic(err)
	}

	fmt.Println(result) // map[apples:5 oranges:3]
}
CSV/TSV Utilities
Reading CSV Headers
package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

func main() {
	// Read CSV header and get field positions
	header, err := gnfmt.ReadHeaderCSV("data.csv", ',')
	if err != nil {
		panic(err)
	}

	// header is a map[string]int with field names and their indices
	fmt.Println(header["name"])  // 0
	fmt.Println(header["email"]) // 1

	// For TSV files, use '\t' as separator
	tsvHeader, _ := gnfmt.ReadHeaderCSV("data.tsv", '\t')
	fmt.Println(tsvHeader)
}
Converting Records to CSV/TSV
package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

func main() {
	record := []string{"John Doe", "john@example.com", "Has \"quotes\""}

	// Convert to CSV (comma-separated)
	csvLine := gnfmt.ToCSV(record, ',')
	fmt.Println(csvLine)
	// John Doe,john@example.com,"Has ""quotes"""

	// Convert to TSV (tab-separated)
	tsvLine := gnfmt.ToCSV(record, '\t')
	fmt.Println(tsvLine)
	// John Doe	john@example.com	"Has ""quotes"""
}
Normalizing Row Sizes
package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

func main() {
	// Truncate or expand rows to match expected size
	row := []string{"a", "b", "c", "d", "e"}

	// Truncate to 3 fields
	normalized := gnfmt.NormRowSize(row, 3)
	fmt.Println(normalized) // [a b c]

	// Expand to 7 fields (adds empty strings)
	expanded := gnfmt.NormRowSize(row, 7)
	fmt.Println(expanded) // [a b c d e  ]
}
Time Formatting

Convert seconds into human-readable duration strings:

package main

import (
	"fmt"
	"github.com/gnames/gnfmt"
)

func main() {
	fmt.Println(gnfmt.TimeString(45))        // 00:00:45
	fmt.Println(gnfmt.TimeString(3661))      // 01:01:01
	fmt.Println(gnfmt.TimeString(86400))     // 1 day 00:00:00
	fmt.Println(gnfmt.TimeString(172800))    // 2 days 00:00:00
	fmt.Println(gnfmt.TimeString(90061))     // 1 day 01:01:01
}
Implementing Custom Encoders

The Encoder interface allows you to create custom serialization formats:

package main

import (
	"github.com/gnames/gnfmt"
)

type MyCustomEncoder struct{}

func (e MyCustomEncoder) Encode(input interface{}) ([]byte, error) {
	// Your encoding logic here
	return []byte{}, nil
}

func (e MyCustomEncoder) Decode(input []byte, output interface{}) error {
	// Your decoding logic here
	return nil
}

func main() {
	var encoder gnfmt.Encoder = MyCustomEncoder{}
	// Use your custom encoder
	_, _ = encoder.Encode("data")
}
Implementing the Outputter Interface

Create custom output formatters by implementing the Outputter interface:

package main

import (
	"github.com/gnames/gnfmt"
)

type MyOutputter struct{}

func (o MyOutputter) Output(record interface{}, f gnfmt.Format) string {
	// Your custom output logic based on format
	return ""
}

func main() {
	var outputter gnfmt.Outputter = MyOutputter{}
	format, _ := gnfmt.NewFormat("csv")
	result := outputter.Output("data", format)
	_ = result
}

API Documentation

For complete API documentation, visit GoDoc.

License

See the LICENSE file for details.

Documentation

Overview

Example
var enc Encoder
var err error
enc = GNjson{Pretty: true}
ary1 := []int{1, 2, 3}
jsonRes, err := enc.Encode(ary1)
if err != nil {
	panic(err)
}
var ary2 []int
err = enc.Decode(jsonRes, &ary2)
if err != nil {
	panic(err)
}
fmt.Println(ary1[0] == ary2[0])
Output:

true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormRowSize added in v0.4.4

func NormRowSize(row []string, fieldsNum int) []string

NormRowSize takes a row with less or more fields than required and either truncates it, or expands with empty fields to fit to the fieldsNum size.

func Ppr added in v0.3.0

func Ppr(obj interface{}) string

Ppr is a pretty print of an object

func ReadHeaderCSV

func ReadHeaderCSV(path string, sep rune) (map[string]int, error)

ReadHeaderCSV only reads the first line of a CSV/TSV input. It takes a path to a CSV/TSV-encoded file and a separator character. It returns back a map with name of a field, and its index. It also returns an error, if the header could not be read.

func TimeString added in v0.4.0

func TimeString(secs float64) string

func ToCSV

func ToCSV(record []string, sep rune) string

ToCSV takes a slice of strings and converts them to a CSV/TSV row with '"' as a field quote. On Windows machine the row ends with '\r\n', in all other cases with '\n'

Types

type BadRow added in v0.4.5

type BadRow int

BadRow type describes different scenarios of processing rows with wrong number of fields.

const (
	// ErrorBadRow means that an error will be returned when a row with wrong
	// number of fields is encountered.
	ErrorBadRow BadRow = iota

	// SkipBadRow means that rows with wrong number of fields will not be
	// processed.
	SkipBadRow

	// ProcessBadRow means processing bad row hoping for the best.
	ProcessBadRow
)

type Encoder

type Encoder interface {
	//Encode takes a Go object and converts it into bytes
	Encode(input interface{}) ([]byte, error)
	// Decode takes an input of bytes and decodes it into Go object.
	Decode(input []byte, output interface{}) error
}

Encoder interface allows to switch between different encoding types.

type Format

type Format int

Format sets available output formats

const (
	// FormatNone is for cases when format is not set yet.
	FormatNone Format = iota

	// CSV sets output to comma-separated values.
	CSV

	// CompactJSON sets output into one-liner JSON.
	CompactJSON

	// PrettyJSON sets output into easier to read JSON with new lines and
	// indentations.
	PrettyJSON

	// TSV sets output to tab-separated values.
	TSV
)

func NewFormat

func NewFormat(s string) (Format, error)

NewFormat is a constructor that converts a string into a corresponding format. If string cannot be converted, the constructor returns an error and and FormatNone format.

func (Format) String

func (f Format) String() string

String representation of a format.

type GNgob

type GNgob struct{}

GNgob is for serializing data into gob format.

func (GNgob) Decode

func (e GNgob) Decode(input []byte, output interface{}) error

Decode deserializes gob bytes into a go object. It returns an error if decoding fails.

func (GNgob) Encode

func (e GNgob) Encode(input interface{}) ([]byte, error)

Encode takes an object and serializes it into gob blob. It returns an error in case of encoding problems.

type GNjson

type GNjson struct {
	Pretty bool
}

GNjson allows to decode and encode JSON format.

func (GNjson) Decode

func (e GNjson) Decode(input []byte, output interface{}) error

Decode converts JSON into a go object. If decoding breaks, it returns an error.

func (GNjson) Encode

func (e GNjson) Encode(input interface{}) ([]byte, error)

Encode takes an object and coverts it into JSON. It returns an error if the encoding fails.

func (GNjson) Output

func (e GNjson) Output(input interface{}, f Format) string

Output converts an object into a JSON string. It takes an object and a format and returns the corresponding JSON string. In case of a problem it returns an empty string.

type Outputter

type Outputter interface {
	// FormattedOutput takes a record and returns a string representation of
	// the record accourding to supplied format.
	Output(record interface{}, f Format) string
}

Outputter interface us a uniform way to create an output of a datum

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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