如何使用Go的net/http检查POST表单中是否存在某个值?

huangapple go评论115阅读模式
英文:

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

解析表单并检查在提交的表单中是否设置了键。

  1. req.ParseForm()
  2. 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.

  1. req.ParseForm()
  2. hasKey := req.PostForm.Has("key")

huangapple
  • 本文由 发表于 2022年6月16日 13:30:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/72640915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定