获取 go 语言表单的未收到数据



这是astaxie书中的简单形式 当我尝试"/登录"时,我得到

No Data received { Unable to load the webpage because the server sent no data.   Error code: ERR_EMPTY_RESPONSE }

代码如下:

主去

package main
import (
    "fmt"
    "html/template"
    "net/http"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello astaxie!") // write data to response
}
func login(w http.ResponseWriter, r *http.Request) {
    fmt.Println("method:", r.Method) //get request method
    if r.Method == "GET" {
      t, err :=template.New("").Parse(loginHtml)
      if err != nil {
          panic(err)
      }
      const loginHtml = `
      <html>
      <head>
      <title></title>
      </head>
      <body>
      <form action="/login" method="post">
          Username:<input type="text" name="username">
          Password:<input type="password" name="password">
          <input type="submit" value="Login">
      </form>
      </body>
      </html>
      `
    }    else {
        r.ParseForm()
        // logic part of log in
        fmt.Println("username:", r.PostFormValue("username"))
        fmt.Println("password:", r.PostFormValue("password"))
    }
}

func main() {
    http.HandleFunc("/", sayhelloName) // setting router rule
    http.HandleFunc("/login", login)
   http.ListenAndServe(":9090", nil) // setting listening port
}
#login.gtpl
<html>
<head>
<title></title>
</head>
<body>
<form action="/login" method="post">
    Username:<input type="text" name="username">
    Password:<input type="password" name="password">
    <input type="submit" value="Login">
</form>
</body>
</html>
Any idea??

您的原始问题(已多次编辑(的问题在于您的ParseFiles()函数失败,它无法读取您的模板文件。你不知道这一点,因为它返回的error你只是丢弃了。永远不要那样做!您至少可以做的是打印错误或在发生错误时调用panic(err)。如果你这样做,你会立即看到原因。

如果指定相对路径,则必须将login.gtpl文件放置在启动应用的工作目录中。或者指定绝对路径。

你也可以像这样把你的HTML源代码放到你的Go文件中,直到你把事情整理出来:

t, err := template.New("").Parse(loginHtml)
if err != nil {
    panic(err)
}
t.Execute(w, nil)
// ... the rest of your code

// At the end of your .go source file (outside of login() func) insert:
const loginHtml = `
<html>
<head>
<title></title>
</head>
<body>
<form action="/login" method="post">
    Username:<input type="text" name="username">
    Password:<input type="password" name="password">
    <input type="submit" value="Login">
</form>
</body>
</html>
`

注意#1:

由于您的 HTML 模板只是一个静态 HTML,因此在其当前形式中,您只需将其发送到输出,而无需从中构建和执行模板:

// Instead of calling template.New(...).Parse(...) and t.Execute(...), just do:
w.Write([]byte(loginHtml))

注意#2:

Request.Form仅在调用Request.ParseForm()后可用,因此请在访问它之前执行此操作。此外,对于POST表单,您可能希望改用Request.PostForm

作为替代方法,您可以使用 Request.PostFormValue() 方法,如果尚未调用它,它会自动为您执行此操作:

fmt.Println("username:", r.PostFormValue("username"))
fmt.Println("password:", r.PostFormValue("password"))

最新更新