DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

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

Top comments (0)