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
方案二:
type s struct {
productid int `json:"product_id"`
f float64 `json:"f"`
}
s := s{product: 12, f: 2.7}
jsondata, _ := json.marshal(s)
var m map[string]interface{}
json.unmarshal(jsondata, &m)
fmt.println(reflect.typeof(m["product_id"]))
fmt.println(reflect.typeof(m["f"]))
decoder := jsoniter.newdecoder(bytes.newreader(jsondata))
decoder.usenumber()
decoder.decode(&m)
fmt.println(reflect.typeof(m["product_id"].(json.number).int64))
fl, _ := m["f"].(json.number).float64()
fmt.println(reflect.typeof(fl))
golang读取response body超时问题
context deadline exceeded(client.timeout or context cancellation while reading body)
问题描述
当使用io.copy进行对网络请求的文件进行保存到本地时,在文件未完全保存时抛出此错误
问题原因
由于在构建http client 时指定了超时时间,即
return &http.client{
timeout: 60 * time.second,
}故此,当时间超过此时间时context会结束
解决办法
目前使用增加超时时间,暂时解决这个问题
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论