SoFunction
Updated on 2025-03-01

Solve the pitfalls encountered when golang reads http body

When the server parses the http body to map[string]interface{}, the cli passes the int type, while the server can only assert as float64, and cannot directly assert as int that received what should be int type as 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: "This software logo is so ugly",
 Image: ";",
 Longitude: 106.3037109375,
 Latitude: 38.5137882595,
 Grade:9.9,
 }
 reqByte,err:=(myReq)
 req, err := ("POST", url, (reqByte))
 if err != nil {
 return
 }
 //Set request header ("Content-Type", "application/json")
 cli := {
 Timeout: 45 * ,
 }
 resp, err := (req)
 if err != nil {
 return
 }
 out, err := ()
 if err != nil {
 return
 }
 (string(out))
}

server

func SubmitV2(c *) {
 resp := &{}
 obj:=make(map[string]interface{})
 var buf []byte
 var err error
 buf, err =(c. )
 if err!=nil {
 return
 }
 err=(buf,&obj)
 if err!=nil {
 return
 }
 ("product_id:",(obj["product_id"]))
 ("image:",(obj["image"]))
 (obj)
 productId:=obj["product_id"].(float64)
 //Note that it will cause an error when asserting it as an int type here  = ((buf))
 if !checkProduct(int(productId)){
  = -1
  = "xxxxxx"
 (, resp)
 return
 }
 url :=  + "/api/v1/submit"
 err = http_utils.PostAndUnmarshal(url, , nil, resp)
 if err != nil {
 (err).Errorln("Submit: error")
  = -1
  = "Submit"
 }
 (, resp)
}

Print type, find product_id is float64 type

reason:The number types in json do not correspond to int, and they are all float64 after parsing.

Supplement: Golang Web obtains the content of the http request message body body

Sample code:

package main
import (
 "fmt"
 "net/http"
)
func headerBody(rw , r *) {
 // Get the content length of the request message len := 
 // Create a new byte slice, the length is the same as the content of the request message body := make([]byte, len)
 // Read the request body of r and read the specific content into the body (body)
 // Write the content of the byte slice into the corresponding message (rw, body)
}
func main() {
 server := {
 Addr: "127.0.0.1:http",
 }
 ("/", headerBody)
 ()
}

Notice:

1. The get request does not contain the message subject.

2. The post request does not contain the message subject.

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.