當(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ù)字類型沒有對(duì)應(yīng)int,解析出來都是float64
補(bǔ)充:Golang Web 獲取 http 請(qǐng)求報(bào)文主體 body 的內(nèi)容
示例代碼:
package main import ( "fmt" "net/http" ) func headerBody(rw http.ResponseWriter, r *http.Request) { // 獲取請(qǐng)求報(bào)文的內(nèi)容長度 len := r.ContentLength // 新建一個(gè)字節(jié)切片,長度與請(qǐng)求報(bào)文的內(nèi)容長度相同 body := make([]byte, len) // 讀取 r 的請(qǐng)求主體,并將具體內(nèi)容讀入 body 中 r.Body.Read(body) // 將字節(jié)切片內(nèi)容寫入相應(yīng)報(bào)文 fmt.Fprintln(rw, body) } func main() { server := http.Server{ Addr: "127.0.0.1:http", } http.HandleFunc("/", headerBody) server.ListenAndServe() }
注意:
1. get 請(qǐng)求不包含報(bào)文主體。
2. post 請(qǐng)求不包含報(bào)文主體。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:宜春 武漢 松原 泰安 河池 鷹潭 保定 黔西
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《解決golang讀取http的body時(shí)遇到的坑》,本文關(guān)鍵詞 解決,golang,讀取,http,的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。