golang ParseForm post数据

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

一、form.html

文件内容如下:



<br />



  


二、main.go

main.go内容如下:



<br />
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)
    }
}
执行结果如下:



<img src="https://www.361way.com/wp-content/uploads/2019/03/ParseForm.png" width="615" height="197" title="ParseForm" alt="ParseForm" />



<br />

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注