golang讀取http的body時(shí)遇到的坑及解決
golang讀取http的body時(shí)遇到的坑
當(dāng)服務(wù)端對(duì)http的body進(jìn)行解析到map[string]interface{}時(shí),會(huì)出現(xiàn)cli傳遞的是int類型,而服務(wù)端只能斷言成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: "這個(gè)軟件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
}
//設(shè)置請(qǐng)求頭
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類型會(huì)出錯(cuò)
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)
}
打印類型,發(fā)現(xiàn)product_id是float64類型
原因:
json中的數(shù)字類型沒(méi)有對(duì)應(yīng)int,解析出來(lái)都是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超時(shí)問(wèn)題
context deadline exceeded(Client.Timeout or context cancellation while reading body)
問(wèn)題描述
當(dāng)使用io.copy進(jìn)行對(duì)網(wǎng)絡(luò)請(qǐng)求的文件進(jìn)行保存到本地時(shí),在文件未完全保存時(shí)拋出此錯(cuò)誤
問(wèn)題原因
由于在構(gòu)建http client 時(shí)指定了超時(shí)時(shí)間,即
return &http.Client{
Timeout: 60 * time.Second,
}故此,當(dāng)時(shí)間超過(guò)此時(shí)間時(shí)context會(huì)結(jié)束
解決辦法
目前使用增加超時(shí)時(shí)間,暫時(shí)解決這個(gè)問(wèn)題
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
golang sql語(yǔ)句超時(shí)控制方案及原理
一般應(yīng)用程序在執(zhí)行一條sql語(yǔ)句時(shí),都會(huì)給這條sql設(shè)置一個(gè)超時(shí)時(shí)間,本文主要介紹了golang sql語(yǔ)句超時(shí)控制方案及原理,具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12
Go語(yǔ)言中html/template模塊詳細(xì)功能介紹與示例代碼
這篇文章主要介紹了Go語(yǔ)言中html/template模塊詳細(xì)功能介紹與示例代碼,這里說(shuō)的是go 語(yǔ)言中自帶的包html/template里的一些基本操作,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-03-03
K8s部署發(fā)布Golang應(yīng)用程序的實(shí)現(xiàn)方法
本文主要介紹了K8s部署發(fā)布Golang應(yīng)用程序的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07

