gpt4 book ai didi

http - 如何在POST请求中获取参数

转载 作者:行者123 更新时间:2023-12-01 22:33:25 24 4
gpt4 key购买 nike

我正在尝试获取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: 
为什么不采用参数?我做错了什么?

最佳答案

在将主体作为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

关于http - 如何在POST请求中获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64081780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com