通过 form 获取表单及POST 数据

golang 提供 Form、PostForm、MultipartForm 三种方式来获取表单及POST 数据

r.Form

Form 获取的数据保护 POST 数据和 URL 数据

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Index ..."))
		r.ParseForm()
		fmt.Fprintln(w, r.Form)
	})
	http.ListenAndServe(":80", nil)
}

测试代码

POST  http://localhost/?a=909 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=hhhh&age=9

r.PostForm

r.PostForm 只接收 POST 数据

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Index ..."))
		r.ParseForm()
		fmt.Fprintln(w, r.PostForm)
	})
	http.ListenAndServe(":80", nil)
}