解析来自HTML
的输入。

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

Parse input from HTML <form>

问题

我使用Goji框架运行了一些代码:

package main

import (
    "fmt"
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"])
}

func main() {
    goji.Get("/hello/:name", hello)
    goji.Serve()
}

我希望有人能帮我弄清楚如何在提交HTML表单时将数据发送到Golang代码。

所以,如果有一个带有name属性的输入字段,其值为name,用户在其中输入一个名称并提交,那么在提交的表单页面上,Golang代码将打印出"Hello, name"。

这是我能想到的代码:

package main

import (
    "fmt"
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
    name := r.PostFormValue("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

func main() {
    goji.Handle("/hello/", hello)
    goji.Serve()
}

这是我的hello.html文件:

在body中:

<form action="" method="get">
    <input type="text" name="name" />
</form>

我该如何将hello.html连接到hello.go,以便Golang代码获取输入内容并在提交的表单页面上返回"Hello, name"?

非常感谢您的帮助!

英文:

I got something running with the Goji framework:

package main

import (
        &quot;fmt&quot;
        &quot;net/http&quot;

        &quot;github.com/zenazn/goji&quot;
        &quot;github.com/zenazn/goji/web&quot;
)

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, &quot;Hello, %s!&quot;, c.URLParams[&quot;name&quot;])
}

func main() {
        goji.Get(&quot;/hello/:name&quot;, hello)
        goji.Serve()
}

What I was hoping someone could help me do is figure out how when an HTML form is submitted to send that data to Golang code.

So if there is an input field with the name attribute and the value of that is name and the user types a name in there and submits, then on the form submitted page the Golang code will print hello, name.

Here is what I could come up with:

package main

import(
    &quot;fmt&quot;
    &quot;net/http&quot;

    &quot;github.com/zenazn/goji&quot;
    &quot;github.com/zenazn/goji/web&quot;
)

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.PostFormValue(&quot;name&quot;)
    fmt.Fprintf(w, &quot;Hello, %s!&quot;, name)
}

func main(){
    goji.Handle(&quot;/hello/&quot;, hello)
    goji.Serve()
}

and here is my hello.html file:

in the body:

&lt;form action=&quot;&quot; method=&quot;get&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;name&quot; /&gt;
&lt;/form&gt;

How do I connect hello.html to hello.go so that the Golang code gets what is in the input and returns hello, name in the form submitted page?

I'd greatly appreciate any and all help!

答案1

得分: 20

为了读取HTML表单的值,你首先需要调用r.ParseForm()。然后你可以获取表单的值。

所以这段代码:

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.PostFormValue("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

应该改为:

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    
    // 调用ParseForm使表单字段可用。
    err := r.ParseForm()
    if err != nil {
        // 通过日志处理错误,然后返回
    }
    
    name := r.PostFormValue("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

编辑: 我应该注意到,当学习net/http包时,这一点让我困惑了一段时间。

英文:

In order to read html form values you have to first call r.ParseForm(). The you can get at the form values.

So this code:

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.PostFormValue(&quot;name&quot;)
    fmt.Fprintf(w, &quot;Hello, %s!&quot;, name)
}

Should be this:

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    
    //Call to ParseForm makes form fields available.
    err := r.ParseForm()
    if err != nil {
        // Handle error here via logging and then return            
    }
    
    name := r.PostFormValue(&quot;name&quot;)
    fmt.Fprintf(w, &quot;Hello, %s!&quot;, name)
}

Edit: I should note that this was a point that tripped me up when learning the net/http package

答案2

得分: 6

您的表单输入名称 name 是 go 程序中要获取的键。

<form action="" method="get">
    <input type="text" name="name" />
</form>

您可以使用 FormValue 函数来获取值。
https://golang.org/pkg/net/http/#Request.FormValue

FormValue 函数返回查询中指定组件的第一个值。POST 和 PUT 请求体参数优先于 URL 查询字符串值。FormValue 函数会在必要时调用 ParseMultipartForm 和 ParseForm 函数,并忽略这些函数返回的任何错误。如果键不存在,FormValue 函数返回空字符串。要访问同一键的多个值,请调用 ParseForm,然后直接检查 Request.Form。

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.FormValue("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

如果 FormFile 函数不起作用,最好使用 ParseMultipartForm 函数。
https://golang.org/pkg/net/http/#Request.ParseMultipartForm

您可以使用 ParseMultipartForm 函数来解析 multipart/form-data 类型的请求体。整个请求体将被解析,其中最多 maxMemory 字节的文件部分将存储在内存中,其余部分将存储在临时文件中。ParseMultipartForm 函数在必要时调用 ParseForm 函数。调用一次 ParseMultipartForm 后,后续的调用不会产生任何效果。

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.FormValue("name")
    r.ParseMultipartForm(32 << 20)
    fmt.Fprintf(w, "Hello, %s!", name)
}

此外,除非在提交表单后进行某种处理,否则 form 是无用的。请根据需要使用它。

英文:

Your form input name, name is the key to be fetched by go program.

&lt;form action=&quot;&quot; method=&quot;get&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;name&quot; /&gt;
&lt;/form&gt;

You can use FormValue
https://golang.org/pkg/net/http/#Request.FormValue
> FormValue returns the first value for the named component of the
> query. POST and PUT body parameters take precedence over URL query
> string values. FormValue calls ParseMultipartForm and ParseForm if
> necessary and ignores any errors returned by these functions. If key
> is not present, FormValue returns the empty string. To access multiple
> values of the same key, call ParseForm and then inspect Request.Form
> directly.

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.FormValue(&quot;name&quot;)
    fmt.Fprintf(w, &quot;Hello, %s!&quot;, name)
}

If FormFile doesn't works, better use ParseMultiForm
https://golang.org/pkg/net/http/#Request.ParseMultipartForm

You can use ParseMultipartForm

> ParseMultipartForm parses a request body as multipart/form-data. The
> whole request body is parsed and up to a total of maxMemory bytes of
> its file parts are stored in memory, with the remainder stored on disk
> in temporary files. ParseMultipartForm calls ParseForm if necessary.
> After one call to ParseMultipartForm, subsequent calls have no effect

func hello(c web.C, w http.ResponseWriter, r *http.Request){
    name := r.FormValue(&quot;name&quot;)
	r.ParseMultipartForm(32 &lt;&lt; 20)
    fmt.Fprintf(w, &quot;Hello, %s!&quot;, name)
}

Also, a form is useless unless some kind of processing takes place after the form is submitted. So use it accordingly.

huangapple
  • 本文由 发表于 2014年4月25日 08:45:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/23282311.html
匿名

发表评论

匿名网友

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

确定