【问题标题】:How to get parameters in POST request如何在 POST 请求中获取参数
【发布时间】:2021-01-12 19:58:06
【问题描述】:

我正在尝试获取 POST 请求中的参数,但我无法做到,我的代码是:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", hello)
    fmt.Printf("Starting server for testing HTTP POST...\n")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

func hello(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.Error(w, "404 not found.", http.StatusNotFound)
        return
    }
    switch r.Method {
    case "POST":
        // Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
        if err := r.ParseForm(); err != nil {
            fmt.Fprintf(w, "ParseForm() err: %v", err)
            return
        }
        name := r.Form.Get("name")
        age := r.Form.Get("age")
        fmt.Print("This have been received:")
        fmt.Print("name: ", name)
        fmt.Print("age: ", age)
    default:
        fmt.Fprintf(w, "Sorry, only POST methods are supported.")
    }
}

我在终端中发出 POST 请求如下:

curl -X POST -d '{"name":"Alex","age":"50"}' localhost:8080

然后输出是:

This have been received:name: age: 

为什么不带参数?我做错了什么?

【问题讨论】:

  • 您需要先执行r.ParseForm(),它会解析来自 URL 的原始查询并填充表单。
  • A 正在这样做,在 case: POST 之后,在 if 条件中
  • 您正在发送带有 json 数据的 POST。设置Content-Type标头,使用json.Decode解析go中的数据。
  • 或者您可以将 curl 命令更改为以 urlencoded 形式发布,以匹配代码的预期: curl -X POST -d name=Alex -d age=50 localhost:8080
  • 这能回答你的问题吗? Handling JSON Post Request in Go

标签: http go post


【解决方案1】:

当您将正文作为 json 对象传递时,您最好定义一个与该对象匹配的 Go 结构并将 request 正文解码为该对象。

type Info struct {
    Name string
    Age  int
}
info := &Info{}
if err := json.NewDecoder(r.Body).Decode(info); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
_ = json.NewEncoder(w).Encode(info)

你可以找到完整的工作代码here

$ curl -X POST -d '{"name":"Alex","age":50}' localhost:8080

这个POST 请求现在工作正常。

您可以随意修改Go 结构和响应object

【讨论】:

  • 非常感谢您的认可,非常感谢!
猜你喜欢
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多