Golang解析表单

huangapple go评论88阅读模式
英文:

Golang parse form

问题

如果我有以下表单设置:

{{ 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 }}

那么我该如何正确提取这些数据呢?请注意,.Scores 可能包含多个结构体。

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()) // 无法调用非函数 r.Form(类型为 url.Values)
    fmt.Printf("%+v\n", r.FormValue("rating")) // 返回空值
}
英文:

If I have the following form setup:

{{ 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 then extract that data correctly? Knowing that there .Scores can contain multiple structs

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
}

答案1

得分: 16

表单键看起来像rating[id],其中id是一个值标识符。要获取其中一个值,请在替换实际的id值后调用r.FormValue("rating[id]")

我建议打印表单以查看发生了什么:

fmt.Printf("%+v\n", r.Form)  // Form后面没有括号,Form不是一个函数

form是一个url.Values。url.Values是一个map[string][]string。您可以按以下方式遍历表单:

for key, values := range r.Form {   // 遍历map
  for _, value := range values {    // 遍历[]string
     fmt.Println(key, value)
  }
}
英文:

The form keys look like rating[id] where id is a value identifier. To get one of the values, call r.FormValue("rating[id]") after substituting id for an actual id value.

I suggest printing the form to see what's going on:

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

The form is an url.Values. An url.Values is a map[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)
  }
}

答案2

得分: 8

对于其他正在寻找答案的人,我发现Gorilla的schema非常有帮助。它允许您将表单解析为结构体,并支持数组和嵌套结构体。当您将其与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"`
    // 自定义映射用于表单输入"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>
英文:

For others that are looking answers for this I found Gorilla's schema really helpful. It allows you to parse forms to structs and has support for arrays and nested structs. When you combine that with guregu's null package you can easily parse sructs with optional fields.

Example Go:

package models

import (
    &quot;github.com/gorilla/schema&quot;
    &quot;gopkg.in/guregu/null.v3&quot;
)

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

Example html

&lt;form&gt;
    &lt;input type=&quot;text&quot; name=&quot;user_name&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;EmailAddress&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;OptionalField&quot;&gt;
&lt;/form&gt;

huangapple
  • 本文由 发表于 2015年2月1日 11:15:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/28259063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定