defaults

package module
v0.1.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: May 31, 2025 License: MIT Imports: 6 Imported by: 0

README

go-defaults

Go Report Card Go CI codecov

go-defaults provides functionality to parse and set default values for struct fields based on their "default" tags

Table of Contents
  1. About The Project
  2. Features
  3. Getting Started
  4. Usage
  5. Supported/Unsupported Field Type
  6. License
  7. Contact

About The Project

The defaults package simplifies the process of setting default values for struct fields in Go when they are unset (i.e., at their zero value or nil for pointers). Instead of manually checking each field for its zero value and assigning defaults, defaults uses struct tags to automatically parse and set default values, making your code cleaner and more maintainable. This project was inspired by the need for a streamlined, reusable solution to initialize struct fields with predefined defaults, especially in scenarios involving configuration structs, data models, or nested structures.

Key Features

  • Automatic Default Value Setting: The Defaults function processes a non-nil pointer to a struct, setting default values for exported fields based on their "default" tags (configurable via the package-level Tag variable).

  • Recursive Struct Handling: Nested structs are processed recursively, applying default values to their fields.

  • Broad Type Support: Supports a wide range of field types, including numeric types, strings, booleans, maps, slices, arrays, and their pointers. See Supported/Unsupported Field Types

  • Robust Error Handling: Returns errors for invalid inputs, unexported fields, empty tags (for non-struct fields), parsing failures, out-of-range values, or unsupported types.

Getting Started

Note that we only supports the two most recent minor versions of Go.

go get github.com/lthphuw/go-defaults@latest

Usage

With go-defaults, you can define defaults in struct tags and let the Defaults function handle initialization:

type Config struct {
    Port int    `default:"8080"`
    Host string `default:"localhost"`
}

func main() {
    var config Config
    // Load from env
    // ...

    // Set defaults
    if err := defaults.Defaults(&config); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Port: %d, Host: %s\n", config.Port, config.Host)
    // Output: Port: 8080, Host: localhost
}

This approach reduces boilerplate code, improves readability, and ensures consistent default value handling across your application.

Here’s a another complete example demonstrating various field types:

package main

import (
    "fmt"
    defaults "github.com/lthphuw/go-defaults"
)

type Nested struct {
    Value int `default:"100"`
}

type Example struct {
    ID      int            `default:"123"`
    Name    *string        `default:"hello"`
    Data    map[string]any `default:"{\"key\":\"value\",\"num\":42}"`
    Numbers [3]int         `default:"[1,2,3]"`
    Nested  Nested
}

func main() {
    var s Example
    if err := defaults.Defaults(&s); err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Printf("ID: %d, Name: %v, Data: %v, Numbers: %v, Nested.Value: %d\n",
        s.ID, *s.Name, s.Data, s.Numbers, s.Nested.Value)
}

Output:

ID: 123, Name: hello, Data: map[key:value num:42], Numbers: [1 2 3], Nested.Value: 100

Supported/Unsupported Field Type

Supported Field Types and Example Tags

The Defaults function supports the following field types with their respective "default" tag formats:

  • Numeric Types:

    • int: default:"123"

    • int8: default:"127"

    • int16: default:"32767"

    • int32: default:"2147483647"

    • int64: default:"9223372036854775807"

    • uint: default:"123"

    • uint8: default:"255"

    • uint16: default:"65535"

    • uint32: default:"4294967295"

    • uint64: default:"18446744073709551615"

    • float32: default:"3.14"

    • float64: default:"3.14159265359"

    • complex64: default:"1+2i"

    • complex128: default:"1.5+2.5i"

  • string: default:"hello"

  • bool: default:"true"

  • map (e.g., map[string]any): default:"{"key":"value","num":42}"

  • slice (e.g., []string): default:"["a","b","c"]"

  • array (e.g., [3]int): default:"[1,2,3]"

struct: triggers recursive default setting for nested fields.

Pointers to Above Types:

  • \*int: default:"123"

  • \*string: default:"hello"

  • \*map[string]any: default:"{"key":"value"}"

  • \*[]string: default:"["a","b"]"

  • \*[3]int: default:"[1,2,3]"

  • \*struct: triggers recursive default setting for nested fields.

  • ...

Unsupported Field Types

The following types are not supported by Defaults:

  • Function types (e.g., func(), *func())

  • Channels (e.g., chan int)

  • Interfaces

  • Unsafe pointers (e.g., unsafe.Pointer)

  • Any other types not listed above

License

This project is licensed under the MIT License – see the LICENSE file for details.

Contact

Maintained by Phu.
For questions, feedback, or support, please contact: lthphuw@gmail.com

(back to top)

Documentation

Overview

Package defaults provides functionality to parse and set default values for struct fields based on their "default" tags. The Defaults function processes a non-nil pointer to a struct, setting default values for exported fields that are unset (zero values for non-pointers or nil for pointers) using the tag key specified by the package-level variable Tag (defaulting to "default"). Nested structs are processed recursively. Fields without a "default" tag are skipped unless they are structs or struct pointers.

Supported field types and example default tags:

  • int: `default:"123"`
  • int8: `default:"127"`
  • int16: `default:"32767"`
  • int32: `default:"2147483647"`
  • int64: `default:"9223372036854775807"`
  • uint: `default:"123"`
  • uint8: `default:"255"`
  • uint16: `default:"65535"`
  • uint32: `default:"4294967295"`
  • uint64: `default:"18446744073709551615"`
  • float32: `default:"3.14"`
  • float64: `default:"3.14159265359"`
  • complex64: `default:"1+2i"`
  • complex128: `default:"1.5+2.5i"`
  • string: `default:"hello"`
  • bool: `default:"true"`
  • map (e.g., map[string]any): `default:"{\"key\":\"value\",\"num\":42}"`
  • slice (e.g., []string): `default:"[\"a\",\"b\",\"c\"]"`
  • array (e.g., [3]int): `default:"[1,2,3]"`
  • struct (triggers recursive default setting for nested struct fields)
  • Pointers to the above types (e.g., *int, *string, *map[string]any, *[]string, *[3]int, *struct):
  • *int: `default:"123"`
  • *string: `default:"hello"`
  • *map[string]any: `default:"{\"key\":\"value\"}"`
  • *[]string: `default:"[\"a\",\"b\"]"`
  • *[3]int: `default:"[1,2,3]"`
  • *struct (recursively processes nested struct fields)

Unsupported field types:

  • Function types (e.g., func(), *func())
  • Channels (e.g., chan int)
  • Interfaces
  • Unsafe pointers (e.g., unsafe.Pointer)
  • Any other types not listed above

Default tag values must be valid for the field's type. Numeric types require valid numeric strings, bool requires "true" or "false", strings can be plain or JSON-escaped, and maps/slices/arrays require JSON-formatted strings. Errors are returned for invalid inputs, unexported fields, empty tags (for non-struct fields), parsing failures (e.g., invalid number formats, JSON syntax errors), out-of-range values, or unsupported types. The Defaults function recursively processes nested structs to apply their default tags.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedType = errors.New("unsupported type")

ErrUnsupportedType is an error returned when attempting to parse an unsupported type.

View Source
var Tag = defaultTag

Tag specifies the struct tag key used to parse default values for fields.

Functions

func Defaults

func Defaults(s any) error

Defaults sets default values for struct fields based on their "default" tags.

It takes a pointer to a struct as input and processes each exported field with a "default" tag. If a field is unset (zero value for non-pointers or nil for pointers), the function parses the tag value and sets it according to the field's type. Supported types include int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128, bool, string, time.Duration, map, slice, array, and nested structs (including pointers to these types). The function recursively processes nested structs. It skips unexported fields, non-zero fields, and fields without a "default" tag unless they are structs or struct pointers.

Errors are returned for invalid inputs, unsupported types, or parsing failures.

func ParseArray

func ParseArray(str string, t reflect.Type) (reflect.Value, error)

ParseArray parses a JSON-like string to an array.

func ParseBool

func ParseBool(str string, t reflect.Type) (reflect.Value, error)

ParseBool parses a string to a boolean.

func ParseComplex

func ParseComplex(str string, t reflect.Type) (reflect.Value, error)

ParseComplex parses a string to a complex type (complex64, complex128).

func ParseDuration

func ParseDuration(str string, t reflect.Type) (reflect.Value, error)

ParseDuration parses a string to a time.Duration.

func ParseFloat

func ParseFloat(str string, t reflect.Type) (reflect.Value, error)

ParseFloat parses a string to a float type (float32, float64).

func ParseInt

func ParseInt(str string, t reflect.Type) (reflect.Value, error)

ParseInt parses a string to an integer type (int, int8, int16, int32, int64).

func ParseMap

func ParseMap(str string, t reflect.Type) (reflect.Value, error)

ParseMap parses a JSON-like string to a map.

func ParseSlice

func ParseSlice(str string, t reflect.Type) (reflect.Value, error)

ParseSlice parses a JSON-like string to a slice.

func ParseString

func ParseString(str string, t reflect.Type) (reflect.Value, error)

ParseString parses a string to a string.

func ParseUint

func ParseUint(str string, t reflect.Type) (reflect.Value, error)

ParseUint parses a string to an unsigned integer type (uint, uint8, uint16, uint32, uint64).

func SetDefaultTag

func SetDefaultTag(tag string)

SetDefaultTag sets the tag name of default tag

Types

type ParserFunc

type ParserFunc func(str string, t reflect.Type) (reflect.Value, error)

ParserFunc defines a function type for parsing a string into a reflect.Value based on the specified reflect.Type, returning the parsed value and any error encountered.

Jump to

Keyboard shortcuts

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