Review generated settings updater

from Reflection
Go 1.27 advanced 6 min 4 issues to find

Review this generated updater before it accepts fields from an external request.

Update a non-nil *Settings through edit tags only, reject unknown, nil, or incompatible values without panicking, and never expose AdminToken as writable input.

Go
package config

import "reflect"

type Settings struct {
    Host       string `edit:"host"`
    Port       int    `edit:"port"`
    AdminToken string
}

func Apply(dst any, fields map[string]any) error {
    target := reflect.ValueOf(dst).Elem()
    for name, raw := range fields {
        field := target.FieldByName(name)
        if !field.IsValid() {
            continue
        }
        value := reflect.ValueOf(raw)
        if value.Type().ConvertibleTo(field.Type()) {
            field.Set(value.Convert(field.Type()))
        }
    }
    return nil
}

generated code is illustrative, not from any one model

Open in playground
Report an error