dtpa98038 2014-04-25 00:45
浏览 24
已采纳

解析来自HTML <form>的输入

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()
}

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(
    "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()
}

and here is my hello.html file:

in the body:

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

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!

  • 写回答

2条回答 默认 最新

  • duanfu5239 2014-04-25 04:40
    关注

    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("name")
        fmt.Fprintf(w, "Hello, %s!", 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("name")
        fmt.Fprintf(w, "Hello, %s!", name)
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名