tts

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

README

tts

Simple package to marshall and unmarshall fixed width text to struct

How to use:

package main

import (
	"encoding/json"
	"fmt"

	"github.com/iarief/tts"
)

type User struct {
	FirstName    string  `txt_width:"10" pad_dir:"right" pad_str:" "`
	LastName     string  `txt_width:"10" pad_dir:"right" pad_str:" "`
	IgnoredValue string  `txt_width:"-" json:"-"`
	Age          int     `txt_width:"3" pad_dir:"left" pad_str:"0"`
	Height       float64 `txt_width:"8" pad_dir:"left" pad_str:" "`
}

func main() {
	user := User{"john", "doe", "ignore this", 20, 182.88}
	str, _ := tts.Marshal(&user)
	fmt.Println(str) // "john      doe       020  182.88"

	user2 := User{}
	_ = tts.Unmarshal(str, &user2)
	byteJSON, _ := json.Marshal(user2)
	fmt.Println(string(byteJSON)) // "{\"FirstName\":\"john\",\:LastName\":\"doe\",\"Age\":20,\"Height\":182.88}"
}

Please note while marshaling the string is forced to be the length that is defined in txt_width tag, either by substring or padding (which could be configured in pad tag)

Documentation

Index

Constants

View Source
const (
	// ErrorInvalidWidth is string representation of the error returned
	// when the function is called with an empty string
	ErrorInvalidWidth = "invalid width"
	// ErrorEmptyString is string representatino of the error returned
	// when there are one or more invalid txt_width tag in the struct
	ErrorEmptyString = "string is empty"
	// ErrorEmptyStruct is string representation of the error returned
	// when marshal is called with an empty struct
	ErrorEmptyStruct = "struct is empty"
)

Variables

This section is empty.

Functions

func Marshal

func Marshal(obj interface{}) (str string, err error)

Marshal is a function to marshal struct into string of fixed width determined by the struct tag

func Unmarshal

func Unmarshal(str string, obj interface{}) error

Unmarshal will Unmarshal a fixed width string to a struct, the struct need to have the tag "txt_width" that contains an int, the field would be parsed by it's definition order Use `txt_width:"-"` if you don't want the field to be parsed

Types

This section is empty.

Jump to

Keyboard shortcuts

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