types

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package types provides a type system for converting string values to Go types during request parsing.

It includes built-in extractors for common types and allows registration of custom extractors for domain-specific types.

Index

Constants

This section is empty.

Variables

View Source
var DefaultRegistry = NewRegistry()

DefaultRegistry is the global registry instance

Functions

func Register

func Register(e *Extractor)

Register adds a custom type extractor to the default registry

Types

type Extractor

type Extractor struct {
	// TypeName is the full type name (e.g., "decimal.Decimal", "time.Time")
	TypeName string

	// Import is the import path needed for this type (e.g., "github.com/shopspring/decimal")
	// Leave empty for built-in types
	Import string

	// ParseFunc generates the code to parse a string value into this type.
	// Parameters:
	//   - varName: the variable containing the string value
	//   - fieldName: the struct field name to assign to
	//   - isPointer: whether the field is a pointer type
	// Returns: Go code as a string
	ParseFunc func(varName, fieldName string, isPointer bool) string

	// RequiresError indicates if the parsing can fail and needs error handling
	RequiresError bool
}

Extractor defines how to convert a string value to a specific Go type.

Example:

&Extractor{
    TypeName: "decimal.Decimal",
    Import:   "github.com/shopspring/decimal",
    ParseFunc: func(varName, fieldName string, isPointer bool) string {
        return fmt.Sprintf(`
            if d, err := decimal.NewFromString(%s); err == nil {
                payload.%s = d
            } else {
                return fmt.Errorf("invalid %s: %%w", err)
            }
        `, varName, fieldName, fieldName)
    },
}

func Get

func Get(typeName string) (*Extractor, bool)

Get retrieves an extractor from the default registry

type Registry

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

Registry holds all registered type extractors

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new type registry with built-in types registered

func (*Registry) All

func (r *Registry) All() map[string]*Extractor

All returns all registered extractors

func (*Registry) Get

func (r *Registry) Get(typeName string) (*Extractor, bool)

Get retrieves an extractor for the given type name

func (*Registry) Register

func (r *Registry) Register(e *Extractor)

Register adds a custom type extractor to the registry

Jump to

Keyboard shortcuts

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