golang 解析 Request post的json数据
在Go语言中,可以使用encoding/json包来解析POST请求中的JSON数据。
首先,你需要定义一个结构体来表示JSON数据的结构。例如,如果JSON数据的格式如下:
{
"name": "John",
"age": 30
}
你可以定义一个对应的结构体:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
然后,在处理POST请求的处理函数中,你可以使用json.Unmarshal()函数来解析JSON数据。例如:
func handlePostRequest(w http.ResponseWriter, r *http.Request) {
// 解析JSON数据
var person Person
err := json.NewDecoder(r.Body).Decode(&person)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 打印解析后的数据
fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
// 其他处理逻辑...
}
在上面的代码中,json.NewDecoder(r.Body).Decode(&person)将请求的JSON数据解析到person变量中。如果解析失败,将返回一个错误。
最后,你可以在你的路由处理函数中调用handlePostRequest函数来处理POST请求。
请注意,你需要在处理完请求后关闭请求的Body,以释放资源。可以使用defer r.Body.Close()来实现。
完整的示例代码如下:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func handlePostRequest(w http.ResponseWriter, r *http.Request) {
// 解析JSON数据
var person Person
err := json.NewDecoder(r.Body).Decode(&person)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 打印解析后的数据
fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
// 其他处理逻辑...
}
func main() {
http.HandleFunc("/post", handlePostRequest)
log.Fatal(http.ListenAndServe(":8080", nil))
}
这样,当你向/post发送POST请求时,可以解析请求的JSON数据并进行处理。
原文地址: https://www.cveoy.top/t/topic/hKDu 著作权归作者所有。请勿转载和采集!