當(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)容長(zhǎng)度
len := r.ContentLength
// 新建一個(gè)字節(jié)切片,長(zhǎng)度與請(qǐng)求報(bào)文的內(nèi)容長(zhǎng)度相同
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ò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- 在Golang中使用http.FileServer返回靜態(tài)文件的操作
- 解決golang http.FileServer 遇到的坑
- golang HTTP 服務(wù)器 處理 日志/Stream流的操作
- golang http請(qǐng)求封裝代碼
- 解決golang處理http response碰到的問題和需要注意的點(diǎn)
- Golang 實(shí)現(xiàn)分片讀取http超大文件流和并發(fā)控制