解析来自HTML< form>的输入 [英] Parse input from HTML <form>

查看:115
本文介绍了解析来自HTML< form>的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Goji框架上运行了一些东西:

I got something running with the Goji framework:

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代码.

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.

因此,如果存在一个带有name属性的输入字段,并且该属性的值是name,并且用户在其中输入名称并提交,那么在提交的表单页面上,Golang代码将打印问候,名称.

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.

这是我能想到的:

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文件:

and here is my hello.html file:

在体内:

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

我如何将hello.html连接到hello.go,以便Golang代码获取输入中的内容并返回hello,即表单提交页面中的名称?

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!

推荐答案

要读取html表单值,您必须先调用 r.ParseForm() .您可以获取表单值.

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

因此,此代码:

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

    //Call to ParseForm makes form fields available.
    err := r.ParseForm()
    if err != nil {
        // Handle error here via logging and then return            
    }

    name := r.PostFormValue("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

我应该注意,这是学习net/http软件包时使我绊倒的一点

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

这篇关于解析来自HTML&lt; form&gt;的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆