英文:
How to check if a value is present in a POST form with Go's net/http?
问题
根据文档的说明:
PostFormValue 返回 POST、PATCH 或 PUT 请求体中指定组件的第一个值。
URL 查询参数将被忽略。
如果需要,PostFormValue 会调用 ParseMultipartForm 和 ParseForm,并忽略这些函数返回的任何错误。
如果键不存在,PostFormValue 将返回空字符串。
因此,当 key
在 POST 请求体中不存在时,函数 Request.PostFormValue(key string) string
返回空字符串,但是当 key
存在且其值为空时也会返回空字符串。
我该如何只检查键是否存在于 POST 请求体中,而不考虑其值?
英文:
According to the documentation:
> PostFormValue returns the first value for the named component of the POST, PATCH, or PUT request body.
> URL query parameters are ignored.
> PostFormValue calls ParseMultipartForm and ParseForm if necessary
> and ignores any errors returned by these functions.
> If key is not present, PostFormValue returns the empty string.
So the function Request.PostFormValue(key string) string
returns an empty string when key
does not exist in the POST body, but also when it exists and its value is empty.
How can I only check if the key is in the POST body, regardless of its value?
答案1
得分: 2
解析表单并检查在提交的表单中是否设置了键。
req.ParseForm()
hasKey := req.PostForm.Has("key")
请注意,以上代码是使用Go语言编写的。req.ParseForm()
用于解析HTTP请求中的表单数据,req.PostForm
是一个url.Values
类型的映射,用于存储解析后的表单数据。req.PostForm.Has("key")
用于检查是否设置了名为"key"的键。
英文:
Parse the form and then check to see if the key is set in the post form.
req.ParseForm()
hasKey := req.PostForm.Has("key")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论