在golang中获取post请求中的json数据非常简单,只需使用标准库中的"net/http"和"encoding/json"包即可。

首先,在处理post请求时,我们需要将请求的body内容读取出来,这可以使用"ioutil"包中的"ReadAll()"方法实现:

import (
"fmt"
"io/ioutil"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unable to read request body", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Received body: %s", body)
}

以上代码中,我们使用了"net/http"包中的"ResponseWriter"和"Request"类型来接收和响应请求。读取请求body时,我们使用了"io/ioutil"包中的"ReadAll()"方法。在读取完成后,我们将body内容写回到响应中。

接下来,我们可以将读取到的body内容进行解析,得到json数据。这可以使用"encoding/json"包中的"Unmarshal()"方法实现:

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type User struct {
Name string `json:"name"`
Age  int    `json:"age"`
}
func handler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unable to read request body", http.StatusBadRequest)
return
}
var user User
if err := json.Unmarshal(body, &user); err != nil {
http.Error(w, "Unable to parse request body as JSON", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Received user: %+v", user)
}

在以上代码中,我们定义了一个"User"结构体,该结构体包含"name"和"age"两个字段,这两个字段对应json中的"name"和"age"字段。在处理post请求时,我们首先读取body内容,然后使用"encoding/json"包中的"Unmarshal()"方法将其解析为"User"类型的数据。如果解析出错,则返回错误响应。否则,我们将解析到的"User"数据返回给客户端。

通过以上方法,我们可以轻松地在golang中获取post请求中的json数据。