如果您要查找的是 POST 数据 以 HTML 格式提交,那么这(通常)是请求体中的键-值对。您的答案是正确的,您可以调用 ParseForm(),然后使用 req.Form字段来获得键-值对的映射,但是您也可以调用 FormValue(key)来获得特定键的值。如果需要,这将调用 ParseForm(),并获取值,而不管它们是如何发送的(例如,在查询字符串中还是在请求体中)。
func newHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET params were:", r.URL.Query())
// if only one expected
param1 := r.URL.Query().Get("param1")
if param1 != "" {
// ... process it, will be the first (only) if multiple were given
// note: if they pass in like ?param1=¶m2= param1 will also be "" :|
}
// if multiples possible, or to process empty values like param1 in
// ?param1=¶m2=something
param1s := r.URL.Query()["param1"]
if len(param1s) > 0 {
// ... process them ... or you could just iterate over them without a check
// this way you can also tell if they passed in the parameter as the empty string
// it will be an element of the array that is the empty string
}
}