DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

1 1

Go - Set Parsed form values to Struct

#go
// Set FormValues to struct
func SetFormValueToStruct(values url.Values, structPtr interface{}) error {
    // Get the pointer of struct
    ptr := reflect.ValueOf(structPtr)

    // Get the value of struct
    value := ptr.Elem()

    // Set value to struct field
    valueType := value.Type()
    for i := 0; i < value.NumField(); i++ {
        jsonTag := valueType.Field(i).Tag.Get("json")
        if value.Field(i).CanSet() == false {
            return errors.New("cannot set value to field")
        }
        value.Field(i).Set(reflect.ValueOf(values.Get(jsonTag)))
    }

    return nil
}

// Example
func ExampleSetFormValueToStruct() {
    // Form values
    formValues := url.Values{}
    formValues.Set("test1", "test1_value")
    formValues.Set("test2", "test2_value")

    // Struct that be wanted to set form values.
    structPtr := &TestSetFormValueToStructStruct{}

    // Set
    structWithValuesPtr := apphttputil.SetFormValueToStruct(formValues, structPtr)

    fmt.Printf("%v", structWithValuesPtr)
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay