Golang Syntax Form

If I have the following form installed:

{{ range $key, $value := .Scores }}
    <input id="{{$value.Id}}_rating__1" type="radio" name="rating[{{$value.Id}}]" value="-1">
    <input id="{{$value.Id}}_rating__0" type="radio" name="rating[{{$value.Id}}]" value="0">
    <input id="{{$value.Id}}_rating__2" type="radio" name="rating[{{$value.Id}}]" value="+1">
{{ end }}

How can I extract this data correctly? Knowing that there .Scoresmay contain several structures

func categoryViewSubmit(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("POST")

    fmt.Printf("%+v\n", r.Form()) // annot call non-function r.Form (type url.Values)
    fmt.Printf("%+v\n", r.FormValue("rating")) // Returns nothing
}
+4
source share
2 answers

The keys on the form look like rating[id]where idis the value identifier. To get one of the values, call r.FormValue("rating[id]")after substitution idfor the actual value of id.

I suggest that you print the form to find out what happens:

fmt.Printf("%+v\n", r.Form)  // No () following Form, Form is not a function

form is url.Values , Url.Values - a string [string] []. You can iterate through the form as follows:

for key, values := range r.Form {   // range over map
  for _, value := range values {    // range over []string
     fmt.Println(key, value)
  }
}
+7
source

, , Gorilla . . guregu null, .

Go:

package models

import (
    "github.com/gorilla/schema"
    "gopkg.in/guregu/null.v3"
)

type User struct {
    Id            null.Int    `db:"id" json:"id"`
    // Custom mapping for form input "user_name" 
    Name          string      `db:"user_name" json:"user_name" schema:"user_name"`
    EmailAddress  string      `db:"email_address" json:"email_address"`
    OptionalField null.String `db:"optional_field" json:"optional_field"`
}

html

<form>
    <input type="text" name="user_name">
    <input type="text" name="EmailAddress">
    <input type="text" name="OptionalField">
</form>
+3

All Articles