go 捕获网卡http_解决golang读取http的body时遇到的坑

当服务端对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 请求不包含报文主体。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值