golang的http.Request方法中有 r.Form and r.PostForm两种请求方式。本篇就结合相关示例给出下使用golang的http模块,结合页面post方法,获取相关数据。该例子需创建两个文件form.html 和 main.go。

一、form.html

文件内容如下:

<pre data-language="HTML">```markup

<html>
<head>
  <meta charset="UTF-8" />
</head>
<body>
<div>
  <form method="POST" action="/">
      <label>Name</label><input name="name" type="text" value="" />
      <label>Address</label><input name="address" type="text" value="" />
      <input type="submit" value="submit" />
  </form>
</div>
</body>
</html>

### 二、main.go

main.go内容如下:

```go
package main
import (
    "fmt"
    "log"
    "net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.Error(w, "404 not found.", http.StatusNotFound)
        return
    }
    switch r.Method {
    case "GET":
         http.ServeFile(w, r, "form.html")
    case "POST":
        // Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
        if err := r.ParseForm(); err != nil {
            fmt.Fprintf(w, "ParseForm() err: %v", err)
            return
        }
        fmt.Fprintf(w, "Post from website! r.PostFrom = %v\n", r.PostForm)
        name := r.FormValue("name")
        address := r.FormValue("address")
        fmt.Fprintf(w, "Name = %s\n", name)
        fmt.Fprintf(w, "Address = %s\n", address)
    default:
        fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.")
    }
}
func main() {
    http.HandleFunc("/", hello)
    fmt.Printf("Starting server for testing HTTP POST...\n")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

执行结果如下:

ParseForm
ParseForm