Golang Post 表单使用(上)

表单post 请求的数据格式 是通过表单的content type 来指定的 也就是enctype

表单中enctype 的属性 如果表单中的enctype 是application/x-www-form-urlencoded
那么浏览器将扁担数据编码到查询字符串里 如果enctype 是multipart/form-data 那么每个name-value
都会转换为一个mime 消息部分 每个部分都有自己的content type 和content disposition

简单文本: 表单URL编码
大量数据,例如上传文件,multipart-MIME

go 语言中从request 中获取URL 或者body中提取数据,通过这些字段:

  • Form
  • PostForm
  • MultipartForm

这三个字段中获取数据
Form 里面的数据是key-value 对
通常做法是先调用ParseForm 或者ParseMultipartForm 来解析request
然后相应访问Form PostForm或者multipartForm字段

<!DOCTYPE html> <html lang="en"> <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Form</title> </head> <body>
    <form action="http://localhost:8080/process?first_name=nike" method="POST" enctype="application/x-www-form-urlencoded">
        <input type="text" name="first_name">
        <input type="text" name="last_name">
        <input type="submit">
    </form>

</body>


</html>
func main() {
   server:=http.Server{
	   Addr: "localhost:8080",
   }
   http.HandleFunc("/process",func(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprintln(w,r.Form["first_name"])
	//只想得到first_name中的值可以使用上面方式   [sasd]
	// 如果表单和URL 中有同样的key 那么他们会放在一个切片里  [dasda nike]
	fmt.Fprintln(w,r.PostForm)
	// r.PostForm 只会查询表单里的数据 仅支持enctype="application/x-www-form-urlencoded"
	}
	server.ListenAndServe()


	r.ParseMultipartForm(1024)
	fmt.Fprintln(w,r.MultipartForm)
   //只解析URL 中的参数 FormValue enctype="multipart/form-data"
	fmt.Fprintln(w,r.FormValue("first_name")) 
	//只解析form 中的参数 FormValue enctype="application/x-www-form-urlencoded"
	fmt.Fprintln(w,r.FormValue("first_name"))
	// PostFormValue 只能取post 的值
	fmt.Fprintln(w,r.PostFormValue("first_name"))

要想使用multipartForm 这个字段 首先要调用ParseMultipartForm 这个
方法 该放到会在必要时调用parseform 方法 参数是需要读取数据的长度 multipartForm
只包含表单的key-value 返回的类型是一个struct 而不是map 这个struct 中有两个map
key 是string value 是[]string 空的(key 是string value 是文件)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值