converter

package
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2026 License: Apache-2.0 Imports: 7 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

AutoPDF Struct Converter

The AutoPDF Struct Converter provides automatic conversion from Go structs to AutoPDF config.Variables using reflection and struct tags. This enables seamless integration of complex Go objects into AutoPDF templates.

Features

  • Automatic Conversion: Convert any Go struct to AutoPDF Variables using reflection
  • Struct Tags: Fine-grained control using autopdf struct tags
  • Nested Structures: Support for nested structs with flattening and inlining options
  • Built-in Type Support: Automatic handling of time.Time, time.Duration, url.URL, and more
  • Custom Converters: Register custom converters for specific types
  • Extensible: Implement AutoPDFFormattable interface for custom conversion logic
  • Performance: Efficient reflection-based conversion with caching

Basic Usage

package main

import (
    "time"
    "github.com/BuddhiLW/AutoPDF/pkg/converter"
)

type Document struct {
    Title     string    `autopdf:"title"`
    Author    string    `autopdf:"author"`
    CreatedAt time.Time `autopdf:"created_at"`
    Pages     int       `autopdf:"pages"`
}

func main() {
    doc := Document{
        Title:     "My Document",
        Author:    "John Doe",
        CreatedAt: time.Now(),
        Pages:     42,
    }

    // Create converter with built-in type support
    converter := converter.BuildWithDefaults()
    
    // Convert struct to Variables
    variables, err := converter.ConvertStruct(doc)
    if err != nil {
        panic(err)
    }

    // Use variables in AutoPDF template
    // Template can access: {{.title}}, {{.author}}, {{.created_at}}, {{.pages}}
}

Struct Tags

The autopdf struct tag provides fine-grained control over conversion behavior:

Basic Tag Usage
type User struct {
    Name  string `autopdf:"name"`           // Field name in template
    Email string `autopdf:"email"`          // Field name in template
    Age   int    `autopdf:"age"`            // Field name in template
    ID    int    `autopdf:"-"`              // Skip this field
}
Tag Options
type Advanced struct {
    // Omit empty values
    Name string `autopdf:"name,omitempty"`
    
    // Flatten nested structures (use dot notation)
    User User `autopdf:"user,flatten"`
    
    // Inline nested struct fields at parent level
    Profile User `autopdf:"profile,inline"`
    
    // Flatten slices to comma-separated strings
    Tags []string `autopdf:"tags,flatten"`
    
    // Multiple options
    Data User `autopdf:"data,flatten,omitempty"`
}
Tag Format
  • autopdf:"field_name" - Set field name in template
  • autopdf:"field_name,omitempty" - Skip field if empty
  • autopdf:"field_name,flatten" - Flatten nested structures
  • autopdf:"field_name,inline" - Inline nested struct fields
  • autopdf:"-" - Skip field entirely

Advanced Features

Nested Structures
Default Behavior (Preserves Structure)
type Address struct {
    Street string `autopdf:"street"`
    City   string `autopdf:"city"`
}

type User struct {
    Name    string  `autopdf:"name"`
    Address Address `autopdf:"address"`
}

// Results in nested structure:
// address.street, address.city
Flattening
type User struct {
    Name    string  `autopdf:"name"`
    Address Address `autopdf:"address,flatten"`
}

// Results in flattened structure:
// name, address.street, address.city
Inlining
type User struct {
    Name    string  `autopdf:"name"`
    Address Address `autopdf:"address,inline"`
}

// Results in inlined structure:
// name, street, city
Array and Slice Handling
Default Behavior (SliceVariable)
type Document struct {
    Tags []string `autopdf:"tags"`
}

// Results in SliceVariable for template loops
Flattening to String
type Document struct {
    Tags []string `autopdf:"tags,flatten"`
}

// Results in comma-separated string: "tag1, tag2, tag3"
Built-in Type Support

The converter automatically handles common Go types:

type Data struct {
    CreatedAt time.Time      `autopdf:"created_at"`     // RFC3339 format
    Duration  time.Duration  `autopdf:"duration"`       // String format
    Homepage  url.URL        `autopdf:"homepage"`       // URL string
    UpdatedAt *time.Time     `autopdf:"updated_at"`     // Pointer support
}
Custom Type Conversion
Using AutoPDFFormattable Interface
type CustomType struct {
    Value string
}

func (ct CustomType) ToAutoPDFVariable() (config.Variable, error) {
    return &config.StringVariable{Value: "custom:" + ct.Value}, nil
}

type Document struct {
    Custom CustomType `autopdf:"custom"`
}
Using Custom Converters
type CustomConverter struct{}

func (cc CustomConverter) Convert(value interface{}) (config.Variable, error) {
    // Custom conversion logic
    return &config.StringVariable{Value: "converted"}, nil
}

func (cc CustomConverter) CanConvert(value interface{}) bool {
    _, ok := value.(MyCustomType)
    return ok
}

// Register converter
registry := converter.NewConverterRegistry()
registry.Register(reflect.TypeOf(MyCustomType{}), CustomConverter{})

Converter Builders

BuildWithDefaults
converter := converter.BuildWithDefaults()
// Includes built-in converters with sensible defaults
BuildForTemplates
converter := converter.BuildForTemplates()
// Optimized for template usage with omitempty enabled
BuildForFlattened
converter := converter.BuildForFlattened()
// Flattens nested structures by default
Custom Builder
converter := converter.NewConverterBuilder().
    WithBuiltinConverters().
    WithTimeFormat("2006-01-02").
    WithDurationFormat("seconds").
    WithSliceSeparator(" | ").
    WithDefaultFlatten(true).
    WithOmitEmpty(true).
    Build()

Integration with AutoPDF

Using with Variable Resolver
import (
    "github.com/BuddhiLW/AutoPDF/pkg/api/adapters/variable_resolver"
    "github.com/BuddhiLW/AutoPDF/pkg/converter"
)

// Create converter
converter := converter.BuildWithDefaults()

// Convert struct to Variables
variables, err := converter.ConvertStruct(myStruct)
if err != nil {
    return err
}

// Use with existing AutoPDF pipeline
resolver := variable_resolver.NewVariableResolverAdapter(config, logger)
resolved, err := resolver.Resolve(variables.GetVariables())
Template Usage
% LaTeX template
\documentclass{article}
\begin{document}

\title{My Document}
\author{John Doe}
\date{2025-01-07}

\maketitle

% Access converted variables
Hello, my name is \textbf{John Doe} and I'm 30 years old.

% Access nested structures
My address is: \textbf{123 Main St, Anytown, USA}

% Access arrays (if not flattened)
\begin{itemize}
\foreach \tag in \tags{
    \item \tag
}
\end{itemize}

\end{document}

Performance Considerations

  • Reflection Overhead: The converter uses reflection, which has some overhead
  • Caching: Consider caching converted results for frequently used structs
  • Memory: Large structs with many nested fields may consume more memory
  • Type Safety: Use custom converters for performance-critical types

Error Handling

The converter provides detailed error messages for common issues:

variables, err := converter.ConvertStruct(myStruct)
if err != nil {
    // Handle conversion errors
    log.Printf("Conversion failed: %v", err)
}

Common error scenarios:

  • Invalid struct tags
  • Unsupported types
  • Circular references
  • Conversion failures

Best Practices

  1. Use Struct Tags: Always use autopdf tags for better control
  2. Implement AutoPDFFormattable: For custom types that need special handling
  3. Register Custom Converters: For performance-critical or complex types
  4. Test Conversion: Always test struct conversion with your actual data
  5. Use Appropriate Builders: Choose the right builder for your use case
  6. Handle Errors: Always check for conversion errors
  7. Consider Performance: Cache results for frequently converted structs

Examples

See pkg/api/examples/struct_conversion_example.go for comprehensive examples demonstrating all features.

License

Copyright 2025 AutoPDF BuddhiLW SPDX-License-Identifier: Apache-2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetBuiltinConverterTypes

func GetBuiltinConverterTypes() []reflect.Type

GetBuiltinConverterTypes returns a list of all built-in converter types

func RegisterBuiltinConverters

func RegisterBuiltinConverters(registry *ConverterRegistry) error

RegisterBuiltinConverters registers all built-in converters

func RunDemo

func RunDemo()

RunDemo demonstrates the AutoPDF struct conversion feature

Types

type AutoPDFFormattable

type AutoPDFFormattable interface {
	ToAutoPDFVariable() (config.Variable, error)
}

AutoPDFFormattable allows custom types to define their own conversion

type ConversionOptions

type ConversionOptions struct {
	DefaultFlatten bool
	TagName        string // "autopdf"
	OmitEmpty      bool
}

ConversionOptions configures conversion behavior

type Converter

type Converter interface {
	Convert(value interface{}) (config.Variable, error)
	CanConvert(value interface{}) bool
}

Converter converts Go values to AutoPDF Variables

type ConverterBuilder

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

ConverterBuilder provides a fluent API for converter construction

func NewConverterBuilder

func NewConverterBuilder() *ConverterBuilder

NewConverterBuilder creates a new ConverterBuilder with default options

func (*ConverterBuilder) Build

func (b *ConverterBuilder) Build() *StructConverter

Build creates the StructConverter with the configured options

func (*ConverterBuilder) BuildValidated

func (b *ConverterBuilder) BuildValidated() (*StructConverter, error)

BuildValidated returns construction failures instead of silently omitting capabilities.

func (*ConverterBuilder) Err

func (b *ConverterBuilder) Err() error

Err reports the first construction error accumulated by the fluent builder.

func (*ConverterBuilder) WithBuiltinConverters

func (b *ConverterBuilder) WithBuiltinConverters() *ConverterBuilder

WithBuiltinConverters registers all built-in converters

func (*ConverterBuilder) WithCustomConverter

func (b *ConverterBuilder) WithCustomConverter(typ interface{}, converter Converter) *ConverterBuilder

WithCustomConverter registers a custom converter for a specific type

func (*ConverterBuilder) WithDefaultFlatten

func (b *ConverterBuilder) WithDefaultFlatten(flatten bool) *ConverterBuilder

WithDefaultFlatten sets the default flattening behavior

func (*ConverterBuilder) WithDurationFormat

func (b *ConverterBuilder) WithDurationFormat(format string) *ConverterBuilder

WithDurationFormat sets the default duration format for time.Duration converters

func (*ConverterBuilder) WithOmitEmpty

func (b *ConverterBuilder) WithOmitEmpty(omit bool) *ConverterBuilder

WithOmitEmpty sets the omit empty behavior

func (*ConverterBuilder) WithRegistry

WithRegistry sets the converter registry

func (*ConverterBuilder) WithSliceSeparator

func (b *ConverterBuilder) WithSliceSeparator(separator string) *ConverterBuilder

WithSliceSeparator sets the default separator for slice flattening

func (*ConverterBuilder) WithTagName

func (b *ConverterBuilder) WithTagName(name string) *ConverterBuilder

WithTagName sets the struct tag name to use

func (*ConverterBuilder) WithTimeFormat

func (b *ConverterBuilder) WithTimeFormat(format string) *ConverterBuilder

WithTimeFormat sets the default time format for time.Time converters

type ConverterRegistry

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

ConverterRegistry manages custom converters for specific types

func NewConverterRegistry

func NewConverterRegistry() *ConverterRegistry

NewConverterRegistry creates a new converter registry

func (*ConverterRegistry) Clear

func (r *ConverterRegistry) Clear()

Clear removes all registered converters

func (*ConverterRegistry) Count

func (r *ConverterRegistry) Count() int

Count returns the number of registered converters

func (*ConverterRegistry) Get

func (r *ConverterRegistry) Get(typ reflect.Type) (Converter, bool)

Get retrieves a converter for a specific type

func (*ConverterRegistry) Has

func (r *ConverterRegistry) Has(typ reflect.Type) bool

Has checks if a converter is registered for a specific type

func (*ConverterRegistry) List

func (r *ConverterRegistry) List() []reflect.Type

List returns all registered types

func (*ConverterRegistry) Register

func (r *ConverterRegistry) Register(typ reflect.Type, converter Converter) error

Register registers a converter for a specific type

func (*ConverterRegistry) RegisterBuiltinConverters

func (r *ConverterRegistry) RegisterBuiltinConverters() error

RegisterBuiltinConverters registers all built-in converters

func (*ConverterRegistry) RegisterInterface

func (r *ConverterRegistry) RegisterInterface(typ reflect.Type, converter Converter) error

RegisterInterface registers a converter for an interface type

func (*ConverterRegistry) Unregister

func (r *ConverterRegistry) Unregister(typ reflect.Type)

Unregister removes a converter for a specific type

type DemoStruct

type DemoStruct struct {
	Title     string    `autopdf:"title"`
	Author    string    `autopdf:"author"`
	CreatedAt time.Time `autopdf:"created_at"`
	Tags      []string  `autopdf:"tags,flatten"`
	IsActive  bool      `autopdf:"is_active"`
}

DemoStruct demonstrates the struct conversion feature

type DurationConverter

type DurationConverter struct {
	Format string // "seconds", "milliseconds", "string"
}

DurationConverter converts time.Duration to string

func NewDurationConverter

func NewDurationConverter() *DurationConverter

NewDurationConverter creates a new DurationConverter with default format

func NewDurationConverterWithFormat

func NewDurationConverterWithFormat(format string) *DurationConverter

NewDurationConverterWithFormat creates a new DurationConverter with custom format

func (*DurationConverter) CanConvert

func (dc *DurationConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a time.Duration

func (*DurationConverter) Convert

func (dc *DurationConverter) Convert(value interface{}) (config.Variable, error)

Convert converts time.Duration to StringVariable or NumberVariable

type DurationPtrConverter

type DurationPtrConverter struct {
	Format string // "seconds", "milliseconds", "string"
}

DurationPtrConverter converts *time.Duration to string

func NewDurationPtrConverter

func NewDurationPtrConverter() *DurationPtrConverter

NewDurationPtrConverter creates a new DurationPtrConverter with default format

func NewDurationPtrConverterWithFormat

func NewDurationPtrConverterWithFormat(format string) *DurationPtrConverter

NewDurationPtrConverterWithFormat creates a new DurationPtrConverter with custom format

func (*DurationPtrConverter) CanConvert

func (dpc *DurationPtrConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a *time.Duration

func (*DurationPtrConverter) Convert

func (dpc *DurationPtrConverter) Convert(value interface{}) (config.Variable, error)

Convert converts *time.Duration to StringVariable or NumberVariable

type FieldTag

type FieldTag struct {
	Name      string   // Field name in template
	Omit      bool     // Skip this field (for "-" tag)
	OmitEmpty bool     // Omit if empty value
	Flatten   bool     // Flatten nested structures
	Inline    bool     // Inline nested struct fields
	Options   []string // Additional options
}

FieldTag represents parsed autopdf struct tag

func ParseTag

func ParseTag(tag string) FieldTag

ParseTag parses "autopdf" struct tag Supports formats:

autopdf:"field_name"
autopdf:"field_name,omitempty"
autopdf:"field_name,flatten"
autopdf:"field_name,inline"
autopdf:"-" (skip field)

func (FieldTag) HasOption

func (ft FieldTag) HasOption(option string) bool

HasOption checks if the tag has a specific option

func (FieldTag) IsEmpty

func (ft FieldTag) IsEmpty() bool

IsEmpty returns true if the tag is empty (no name and no options)

func (FieldTag) IsValid

func (ft FieldTag) IsValid() bool

IsValid returns true if the tag is valid

func (FieldTag) String

func (ft FieldTag) String() string

String returns the string representation of the tag

type FloatSliceConverter

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

FloatSliceConverter is a specialized converter for []float64

func NewFloatSliceConverter

func NewFloatSliceConverter() *FloatSliceConverter

NewFloatSliceConverter creates a new FloatSliceConverter

func NewFloatSliceConverterWithSeparator

func NewFloatSliceConverterWithSeparator(separator string) *FloatSliceConverter

NewFloatSliceConverterWithSeparator creates a new FloatSliceConverter with custom separator

func (*FloatSliceConverter) CanConvert

func (fsc *FloatSliceConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a []float64

func (*FloatSliceConverter) Convert

func (fsc *FloatSliceConverter) Convert(value interface{}) (config.Variable, error)

Convert converts []float64 to StringVariable (flattened) or SliceVariable

type IntSliceConverter

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

IntSliceConverter is a specialized converter for []int

func NewIntSliceConverter

func NewIntSliceConverter() *IntSliceConverter

NewIntSliceConverter creates a new IntSliceConverter

func NewIntSliceConverterWithSeparator

func NewIntSliceConverterWithSeparator(separator string) *IntSliceConverter

NewIntSliceConverterWithSeparator creates a new IntSliceConverter with custom separator

func (*IntSliceConverter) CanConvert

func (isc *IntSliceConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a []int

func (*IntSliceConverter) Convert

func (isc *IntSliceConverter) Convert(value interface{}) (config.Variable, error)

Convert converts []int to StringVariable (flattened) or SliceVariable

type SliceConverter

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

SliceConverter converts slices and arrays

func NewSliceConverter

func NewSliceConverter() *SliceConverter

NewSliceConverter creates a new SliceConverter

func NewSliceConverterWithOptions

func NewSliceConverterWithOptions(flatten bool, separator string) *SliceConverter

NewSliceConverterWithOptions creates a new SliceConverter with options

func (*SliceConverter) CanConvert

func (sc *SliceConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a slice or array

func (*SliceConverter) Convert

func (sc *SliceConverter) Convert(value interface{}) (config.Variable, error)

Convert creates SliceVariable or flattened string based on options

func (*SliceConverter) SetElementConverter

func (sc *SliceConverter) SetElementConverter(converter Converter)

SetElementConverter sets the converter for individual elements

type StringSliceConverter

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

StringSliceConverter is a specialized converter for []string

func NewStringSliceConverter

func NewStringSliceConverter() *StringSliceConverter

NewStringSliceConverter creates a new StringSliceConverter

func NewStringSliceConverterWithSeparator

func NewStringSliceConverterWithSeparator(separator string) *StringSliceConverter

NewStringSliceConverterWithSeparator creates a new StringSliceConverter with custom separator

func (*StringSliceConverter) CanConvert

func (ssc *StringSliceConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a []string

func (*StringSliceConverter) Convert

func (ssc *StringSliceConverter) Convert(value interface{}) (config.Variable, error)

Convert converts []string to StringVariable (flattened) or SliceVariable

type StructConverter

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

StructConverter is the main converter for structs

func BuildForFlattened

func BuildForFlattened() *StructConverter

BuildForFlattened creates a StructConverter that flattens nested structures

func BuildForTemplates

func BuildForTemplates() *StructConverter

BuildForTemplates creates a StructConverter optimized for template usage

func BuildWithDefaults

func BuildWithDefaults() *StructConverter

BuildWithDefaults creates a StructConverter with sensible defaults

func NewStructConverter

func NewStructConverter() *StructConverter

NewStructConverter creates a new StructConverter with default options

func NewStructConverterWithOptions

func NewStructConverterWithOptions(options ConversionOptions) *StructConverter

NewStructConverterWithOptions creates a new StructConverter with custom options

func (*StructConverter) ConvertStruct

func (sc *StructConverter) ConvertStruct(v interface{}) (*config.Variables, error)

ConvertStruct converts a struct to Variables using reflection

type TimeConverter

type TimeConverter struct {
	Format string // Default: RFC3339
}

TimeConverter converts time.Time to string

func NewTimeConverter

func NewTimeConverter() *TimeConverter

NewTimeConverter creates a new TimeConverter with default format

func NewTimeConverterWithFormat

func NewTimeConverterWithFormat(format string) *TimeConverter

NewTimeConverterWithFormat creates a new TimeConverter with custom format

func (*TimeConverter) CanConvert

func (tc *TimeConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a time.Time

func (*TimeConverter) Convert

func (tc *TimeConverter) Convert(value interface{}) (config.Variable, error)

Convert converts time.Time to StringVariable

type TimePtrConverter

type TimePtrConverter struct {
	Format string // Default: RFC3339
}

TimePtrConverter converts *time.Time to string

func NewTimePtrConverter

func NewTimePtrConverter() *TimePtrConverter

NewTimePtrConverter creates a new TimePtrConverter with default format

func NewTimePtrConverterWithFormat

func NewTimePtrConverterWithFormat(format string) *TimePtrConverter

NewTimePtrConverterWithFormat creates a new TimePtrConverter with custom format

func (*TimePtrConverter) CanConvert

func (tpc *TimePtrConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a *time.Time

func (*TimePtrConverter) Convert

func (tpc *TimePtrConverter) Convert(value interface{}) (config.Variable, error)

Convert converts *time.Time to StringVariable

type URLConverter

type URLConverter struct{}

URLConverter converts url.URL to string

func NewURLConverter

func NewURLConverter() *URLConverter

NewURLConverter creates a new URLConverter

func (*URLConverter) CanConvert

func (uc *URLConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a url.URL

func (*URLConverter) Convert

func (uc *URLConverter) Convert(value interface{}) (config.Variable, error)

Convert converts url.URL to StringVariable

type URLPtrConverter

type URLPtrConverter struct{}

URLPtrConverter converts *url.URL to string

func NewURLPtrConverter

func NewURLPtrConverter() *URLPtrConverter

NewURLPtrConverter creates a new URLPtrConverter

func (*URLPtrConverter) CanConvert

func (upc *URLPtrConverter) CanConvert(value interface{}) bool

CanConvert checks if the value is a *url.URL

func (*URLPtrConverter) Convert

func (upc *URLPtrConverter) Convert(value interface{}) (config.Variable, error)

Convert converts *url.URL to StringVariable

Jump to

Keyboard shortcuts

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