解决golang读取http的body时遇到的坑

作者:龚常兴 时间:2024-02-13 19:47:32 

当服务端对http的body进行解析到map[string]interface{}时,会出现cli传递的是int类型,而服务端只能断言成float64,而不能将接收到的本该是int类型的直接断言为int

cli


func main(){
url:="http://127.0.0.1:8335/api/v2/submit"
myReq:= struct {
ProductId  int  `json:"product_id"`
Mobile   string `json:"mobile"`
Content  string  `json:"content"`
Grade  float64 `form:"grade" json:"grade"`
Image  string `form:"image" json:"image"`
 Longitude  float64    `json:"longitude"`
Latitude  float64   `json:"latitude"`
}{
ProductId:219,
Mobile:"15911111111",
Content: "这个软件LOGO真丑",
Image: "www.picture.com;www.picture.com",
Longitude: 106.3037109375,
Latitude: 38.5137882595,
Grade:9.9,
}
reqByte,err:=json.Marshal(myReq)
req, err := http.NewRequest("POST", url, bytes.NewReader(reqByte))
if err != nil {
return
}
//设置请求头
req.Header.Add("Content-Type", "application/json")
cli := http.Client{
Timeout: 45 * time.Second,
}
resp, err := cli.Do(req)
if err != nil {
return
}
out, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
fmt.Println(string(out))
}

server


func SubmitV2(c *gin.Context) {
resp := &dto.Response{}
obj:=make(map[string]interface{})
var buf []byte
var err error
buf, err =ioutil.ReadAll(c. Request.Body)
if err!=nil {
return
}
err=json.Unmarshal(buf,&obj)
if err!=nil {
return
}
fmt.Println("product_id:",reflect.TypeOf(obj["product_id"]))
fmt.Println("image:",reflect.TypeOf(obj["image"]))
fmt.Println(obj)
productId:=obj["product_id"].(float64)
//注意,这里断言成int类型会出错
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
if !checkProduct(int(productId)){
resp.Code = -1
resp.Message = "xxxxxx"
c.JSON(http.StatusOK, resp)
return
}
url := config.Optional.OpinionHost + "/api/v1/submit"
err = http_utils.PostAndUnmarshal(url, c.Request.Body, nil, resp)
if err != nil {
logrus.WithError(err).Errorln("Submit: error")
resp.Code = -1
resp.Message = "Submit"
}
c.JSON(http.StatusOK, resp)
}

打印类型,发现product_id是float64类型

原因:json中的数字类型没有对应int,解析出来都是float64

补充:Golang Web 获取 http 请求报文主体 body 的内容

示例代码:


package main
import (
"fmt"
"net/http"
)
func headerBody(rw http.ResponseWriter, r *http.Request) {
// 获取请求报文的内容长度
len := r.ContentLength
// 新建一个字节切片,长度与请求报文的内容长度相同
body := make([]byte, len)
// 读取 r 的请求主体,并将具体内容读入 body 中
r.Body.Read(body)
// 将字节切片内容写入相应报文
fmt.Fprintln(rw, body)
}
func main() {
server := http.Server{
Addr: "127.0.0.1:http",
}
http.HandleFunc("/", headerBody)
server.ListenAndServe()
}

注意:

1. get 请求不包含报文主体。

2. post 请求不包含报文主体。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/weixin_44267448/article/details/105538240

标签:golang,http,body
0
投稿

猜你喜欢

  • python数据清洗系列之字符串处理详解

    2023-08-02 04:00:07
  • 在MySQL中使用XML数据—数据格式化

    2009-12-29 10:26:00
  • CSS实现DIV完美垂直居中(支持多浏览器)

    2007-08-13 09:21:00
  • Python 实现PS滤镜的旋涡特效

    2022-03-03 02:53:52
  • Django项目使用CircleCI的方法示例

    2022-10-17 11:43:24
  • mysql5.6.19下子查询为什么无法使用索引

    2024-01-15 01:04:29
  • Pyqt QImage 与 np array 转换方法

    2022-01-03 01:18:53
  • Python基础教程之增加和去除数字的千位分隔符

    2021-12-04 13:46:12
  • Pytorch 卷积中的 Input Shape用法

    2023-03-27 21:46:35
  • Python实现日期判断和加减操作详解

    2021-06-17 09:20:02
  • 关于go语言编码需要放到src 文件夹下的问题

    2023-07-03 07:34:00
  • SQL的Join使用图解教程

    2012-08-21 10:47:23
  • Python Pycurl的属性与方法案例详解

    2022-09-27 04:57:23
  • ASP在线升级类文件源码

    2008-10-10 13:09:00
  • PDO::lastInsertId讲解

    2023-06-11 14:31:37
  • 总结近几年Pytorch基于Imgagenet数据集图像分类模型

    2023-01-06 01:15:31
  • python统计cpu利用率的方法

    2022-02-05 23:33:44
  • pytorch loss反向传播出错的解决方案

    2023-04-06 07:20:55
  • Python中字符串List按照长度排序

    2023-11-28 21:43:02
  • php下常用表单验证的正则表达式

    2024-05-03 15:35:08
  • asp之家 网络编程 m.aspxhome.com