获取post请求中body的数据
通过ioutil.ReadAll获取
func addmaster(c echo.Context) error {
defer c.Request().Body.Close()
cat := cat{}
data, err := ioutil.ReadAll(c.Request().Body)
if err != nil {
return c.JSON(http.StatusInternalServerError, "error")
}
err = json.Unmarshal(data, &cat)
if err != nil {
return c.JSON(http.StatusInternalServerError, "error")
}
return c.JSON(http.StatusOK, cat)数据流读入内存,后直接使用json.Unmarshal对数据解析
通过json.NewDecoder获取
func addMasterTwo(c echo.Context) error {
defer c.Request().Body.Close()
cat := cat{}
if err := json.NewDecoder(c.Request().Body).Decode(&cat); err != nil {
return c.JSON(http.StatusInternalServerError, "error")
}
return c.JSON(http.StatusOK, cat)
}json.NewDecoder直接将整个json缓冲进内存,然后再进行解析,用于处理json流,对单个json对象的处理效率好像不高
通过框架获取(如:echo)
func addMasterThree(c echo.Context) error {
cat := cat{}
err := c.Bind(&cat)
if err != nil {
return c.JSON(http.StatusInternalServerError, "error")
}
return c.JSON(http.StatusOK, cat)
}
代码简洁不冗余

京公网安备 11010502036488号