Bind Struct Fields From Lookup Tags
Inspect env and default struct tags via reflect.StructTag.Lookup to populate typed string, int, and bool fields from a key-value map cleanly.
Code
package main
import (
"fmt"
"reflect"
"strconv"
)
type ServiceCfg struct {
Host string `env:"APP_HOST" default:"127.0.0.1"`
Port int `env:"APP_PORT" default:"8080"`
Debug bool `env:"APP_DEBUG" default:"false"`
}
func bindConfig(dst any, env map[string]string) error {
val := reflect.ValueOf(dst).Elem()
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fv := val.Field(i)
key, hasEnv := field.Tag.Lookup("env")
raw, ok := env[key]
if !hasEnv || !ok {
def, hasDef := field.Tag.Lookup("default")
if !hasDef {
continue
}
raw = def
}
switch fv.Kind() {
case reflect.String:
fv.SetString(raw)
case reflect.Int:
n, err := strconv.Atoi(raw)
if err != nil {
return fmt.Errorf("%s: %w", field.Name, err)
}
fv.SetInt(int64(n))
case reflect.Bool:
b, err := strconv.ParseBool(raw)
if err != nil {
return fmt.Errorf("%s: %w", field.Name, err)
}
fv.SetBool(b)
}
}
return nil
}
func main() {
var cfg ServiceCfg
err := bindConfig(&cfg, map[string]string{"APP_PORT": "9090", "APP_DEBUG": "true"})
fmt.Printf("bound: %+v err=%v\n", cfg, err)
err = bindConfig(&cfg, map[string]string{"APP_PORT": "bad-port"})
fmt.Println("invalid int:", err)
}Implementation trace — Bind Struct Fields From Lookup Tags
Structurally, expect the functions bindConfig and main and nothing else.
Iteration happens inside for i := 0; i < typ.NumField(); i++ — everything outside it runs once. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Caveats
- Pure standard library implementation — drop it directly into any workspace and execute.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
Entry signature: func bindConfig(dst any, env map[string]string) error
The demo output is labeled (bound:, invalid int:); each label names the call that printed it.
The entry point wires bindConfig together — run it once and the whole demo flows.
Core lines
return fmt.Errorf("%s: %w", field.Name, err)
func main() {
var cfg ServiceCfg
err := bindConfig(&cfg, map[string]string{"APP_PORT": "9090", "APP_DEBUG": "true"})
fmt.Printf("bound: %+v err=%v\n", cfg, err)
err = bindConfig(&cfg, map[string]string{"APP_PORT": "bad-port"})
fmt.Println("invalid int:", err)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.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.
FAQ
- How are errors reported?
- As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- What does Bind Struct Fields From Lookup Tags print when run?
- Run it as a complete program — the output lines carry labels such as `bound:`, `invalid int:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.