Skip to content

Instantly share code, notes, and snippets.

@pavelanni
Created July 11, 2021 01:39
Show Gist options
  • Save pavelanni/5021927367867dc31ce0b464fa5364c1 to your computer and use it in GitHub Desktop.
Save pavelanni/5021927367867dc31ce0b464fa5364c1 to your computer and use it in GitHub Desktop.
My naive attempt to fill a struct from form data -- similar to gorilla/schema, but much simpler
func newHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
files := []string{
templateDir + "/bootstrap.go.html",
templateDir + "/header.go.html",
templateDir + "/new.go.html",
templateDir + "/footer.go.html",
}
tmpl, err := template.ParseFiles(files...)
if err != nil {
log.Fatal(err)
}
err = tmpl.Execute(w, nil)
if err != nil {
log.Fatal(err)
}
return
}
r.ParseForm()
// This is my own attempt to implement something like gorilla.schema
// It was good to use it to learn more about reflect package
// but probably I should use the existing gorilla.schema
v := Visitor{}
vt := reflect.TypeOf(v)
vp := reflect.ValueOf(&v)
vpe := vp.Elem()
for i := 0; i < vt.NumField(); i++ {
if vpe.Field(i).Kind() == reflect.String {
vpe.Field(i).SetString(r.PostForm[vt.Field(i).Tag.Get("form")][0])
}
if vpe.Field(i).Kind() == reflect.Bool {
if len(r.PostForm[vt.Field(i).Tag.Get("form")]) == 1 {
vpe.Field(i).SetBool(true)
} else {
vpe.Field(i).SetBool(false)
}
}
}
fmt.Fprintln(w, v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment