UnmarshalText Decodes Custom Field Types
Decode custom string fields through UnmarshalText so one method owns trimming, parsing, and rejecting invalid duration syntax.
Code
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
erroris 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
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.