Skip to content

Instantly share code, notes, and snippets.

@ftamhar
Last active October 9, 2021 23:04
Show Gist options
  • Save ftamhar/ec78ded566c44b9831a19a3c861c5e1b to your computer and use it in GitHub Desktop.
Save ftamhar/ec78ded566c44b9831a19a3c861c5e1b to your computer and use it in GitHub Desktop.
function to insert struct value from multipart value, tested on fiber framework.
func InsertStructValueFromMultipart(form map[string][]string, tipe interface{}) {
refValue := reflect.ValueOf(tipe)
newTipe := refValue.Elem()
indirect := reflect.Indirect(refValue).Type() // remove pointer
for i := 0; i < indirect.NumField(); i++ {
value := form[indirect.Field(i).Tag.Get("json")]
if len(value) > 0 && value[0] != "" && value[0] != "null" {
newTipe.Field(i).SetString(strings.Trim(value[0], " "))
}
}
}
// /* usage */
// var agendaRequest entities.AgendaRequest
// body, err := c.MultipartForm()
// if err != nil {
// return c.Status(fiber.StatusInternalServerError).JSON(helpers.ErrorResponse(fiber.StatusInternalServerError, err))
// }
// helpers.InsertStructValueFromMultipart(body.Value, &agendaRequest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment