go语言获取表单信息:FormValue(key)和PostFormValue(key)的区别是什么?

ueueq · 2022-06-07 16:01:05 · 1577 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2022-06-07 16:01:05 的主题,其中的信息可能已经有所发展或是发生改变。

小白一枚,今日post提交表单并获取,这两种方法分别在什么场合使用?有什么区别呢?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1577 次点击  ∙  1 赞  
加入收藏 微博
1 回复  |  直到 2022-06-09 15:02:46
jan-bar
jan-bar · #1 · 3年之前

这种追源码就清楚了,PostForm只在下面这里赋值

if r.PostForm == nil {
        if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" {
            r.PostForm, err = parsePostForm(r)
        }
        if r.PostForm == nil {
            r.PostForm = make(url.Values)
        }
    }

查看这部分代码,PostForm只在header为 "application/x-www-form-urlencoded" 时解析body内容。

func parsePostForm(r *Request) (vs url.Values, err error) {
    if r.Body == nil {
        err = errors.New("missing form body")
        return
    }
    ct := r.Header.Get("Content-Type")
    // RFC 7231, section 3.1.1.5 - empty type
    //   MAY be treated as application/octet-stream
    if ct == "" {
        ct = "application/octet-stream"
    }
    ct, _, err = mime.ParseMediaType(ct)
    switch {
    case ct == "application/x-www-form-urlencoded":
        var reader io.Reader = r.Body
        maxFormSize := int64(1<<63 - 1)
        if _, ok := r.Body.(*maxBytesReader); !ok {
            maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
            reader = io.LimitReader(r.Body, maxFormSize+1)
        }
        b, e := io.ReadAll(reader)
        if e != nil {
            if err == nil {
                err = e
            }
            break
        }
        if int64(len(b)) > maxFormSize {
            err = errors.New("http: POST too large")
            return
        }
        vs, e = url.ParseQuery(string(b))
        if err == nil {
            err = e
        }
    case ct == "multipart/form-data":
        // handled by ParseMultipartForm (which is calling us, or should be)
        // TODO(bradfitz): there are too many possible
        // orders to call too many functions here.
        // Clean this up and write more tests.
        // request_test.go contains the start of this,
        // in TestParseMultipartFormOrder and others.
    }
    return
}

因此:PostFormValue(key) 只在上述情况起作用

看了源码:FormValue(key),貌似也会包含PostFormValue的内容。

go都是开源的,有啥不清楚的,看看源码呗,比到处问人快多了。

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传