介绍
利用golang对身体进行读取时会遇到哪些问题?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
当服务端对http的身体进行解析到map [string]接口{}时,会出现cli传递的是int类型,而服务端只能断言成float64,而不能将接收到的本该是int类型的直接断言为int
<代码> cli 代码>
func 主要(){ ,url:=癶ttp://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 ,“形式:“grade", json:“grade"” ,Image string ,“形式:“image", json:“image"” ,,Longitude float64 ,,,“json:“longitude"” ,Latitude float64 ,,“json:“latitude"” ,}{ 219年,ProductId: ,手机:“15911111111”, ,内容:“这个软件标志真丑,, ,形象:“www.picture.com, www.picture.com" ,经度:106.3037109375, ,纬度:38.5137882595, ,成绩:9.9, ,} 呃,reqByte:=json.Marshal (myReq) ,点播,err :=, http.NewRequest (“POST",, url, bytes.NewReader (reqByte)) ,if err  !=, nil { ,返回 ,} ,//设置请求头 ,req.Header.Add (“Content-Type",,“应用程序/json") ,cli :=, http.Client { ,超时:45,*,time.Second, ,} 职责的不同之处是,err :=, cli.Do(要求) ,if err  !=, nil { ,返回 ,} ,,err :=, ioutil.ReadAll (resp.Body) ,if err  !=, nil { ,返回 ,} ,fmt.Println (string ()) }
<代码>服务器代码>
func SubmitV2 (c * gin.Context), { ,resp :=,, dto.Response {} ,obj:=(map [string]接口{}) ,var buf []字节 ,var err 错误 缓冲区的不同之处是,err =ioutil.ReadAll (c只Request.Body) ,if 犯错!=nil { ,返回 ,} ,呃=json.Unmarshal (buf, obj) ,if 犯错!=nil { ,返回 ,} ,fmt.Println (“product_id:“reflect.TypeOf (obj (“product_id"))) ,fmt.Println(“形象:“,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,职责) ,返回 ,} ,url :=, config.Optional.OpinionHost +,“/api/v1/submit"=,,err  http_utils.PostAndUnmarshal (url, c.Request.Body,, nil,,职责) ,if err  !=, nil { ,logrus.WithError (err) .Errorln(“提交:error") resp.Code =, 1=,resp.Message “Submit" ,} ,c.JSON (http.StatusOK,职责) }
打印类型,发现product_id是float64类型
<强>原因:强> json中的数字类型没有对应int,解析出来都是float64
<强>补充:Golang Web获取http请求报文主体身体的内容强>
示例代码:
package 主要 import ( ,“fmt" ,“;net/http" ) func headerBody (rw http.ResponseWriter, r * http.Request), { ,//获取请求报文的内容长度 ,len :=r.ContentLength ,//新建一个字节切片,长度与请求报文的内容长度相同 ,body :=,([]字节,,len) ,//读取,r 的请求主体,并将具体内容读入,body 中 ,r.Body.Read(身体) ,//将字节切片内容写入相应报文 ,fmt.Fprintln (rw,身体) } func main (), { ,server :=, http.Server { ,Addr:“127.0.0.1: http" ,} ,http.HandleFunc (“/?, headerBody) ,server.ListenAndServe () }
<>强注意:强>
1。得到请求不包含报文主体。
2。文章请求不包含报文主体。