首页 > 解决方案 > 如何在 POST 请求中获取参数

问题描述

我正在尝试获取 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: 

为什么它不采用参数?我做错了什么?

标签: httpgopost

解决方案


当您将 body 作为json对象传递时,您最好定义一个Go与该对象匹配的结构并将 body 解码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)

您可以在此处找到完整的工作代码。

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

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

您可以根据需要修改Go结构和响应object


推荐阅读