简体   繁体   English

如何在POST请求中获取参数

[英]How to get parameters in POST request

I am trying to get the parameters made in a POST request, but I am not able to make it, my code is:我试图获取在 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.")
    }
}

I am making the POST request in the terminal as follows:我正在终端中发出 POST 请求,如下所示:

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

And then the output is:然后输出是:

This have been received:name: age: 

Why it is not taking the parameters?为什么它不带参数? What I am doing wrong?我做错了什么?

As you pass your body as a json object, you better define a Go struct matching that object and decode the request body to the object.当您将主体作为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)

You can find the whole working code here .您可以在此处找到完整的工作代码。

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

This POST request is working fine now.这个POST请求现在工作正常。

You could modify the Go struct and also the response object as you like .您可以根据需要修改Go结构体和响应object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM