UnmarshalText Decodes Custom Field Types

Decode custom string fields through UnmarshalText so one method owns trimming, parsing, and rejecting invalid duration syntax.

GoConfig Management

Code

snippet
package main

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

// Timeout parses a duration from a JSON string via encoding.TextUnmarshaler
type Timeout time.Duration

func (t *Timeout) UnmarshalText(text []byte) error {
	parsed, err := time.ParseDuration(strings.TrimSpace(string(text)))
	if err != nil {
		return fmt.Errorf("timeout %q: %w", text, err)
	}
	*t = Timeout(parsed)
	return nil
}

type Config struct {
	Name    string  `json:"name"`
	Timeout Timeout `json:"timeout"`
	Retries int     `json:"retries"`
}

func main() {
	// UnmarshalText receives the string content without the surrounding quotes
	good := []byte(`{"name":"worker","timeout":" 350ms ","retries":4}`)
	var cfg Config
	if err := json.Unmarshal(good, &cfg); err != nil {
		fmt.Println("good:", err)
		return
	}
	fmt.Printf("good: %s timeout=%v retries=%d\n", cfg.Name, time.Duration(cfg.Timeout), cfg.Retries)

	bad := []byte(`{"name":"worker","timeout":"350","retries":4}`)
	var badCfg Config
	fmt.Println("bad:", json.Unmarshal(bad, &badCfg))
}

Behavior at a glance

UnmarshalText Decodes Custom Field Types is built around the functions UnmarshalText and main.

Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.

Watch out for

  • error is part of the return tuple, so every caller decides what failure means.

Applying it

Entry signature: func (t *Timeout) UnmarshalText(text []byte) error

The run prints good:, bad: — each prefix names the step that produced it.

Statements that matter

return fmt.Errorf("timeout %q: %w", text, err)

Interactive Tools for This Topic

FAQ

How should callers handle failures?
No exceptions — `error` returns checked at 2 sites, and callers branch on `err` first.
What does UnmarshalText Decodes Custom Field Types print when run?
No setup needed: run the file and look for labeled lines like `good:`, `bad:` in the output.