1. 程式人生 > >go語言net/http包解析http body之坑

go語言net/http包解析http body之坑

在Server端解析HTTP請求的時候,
func ProcScaleOutReq(rsp http.ResponseWriter, req *http.Request) {
   req.ParseForm()

   //bodyStr := [1024]byte{}
   //bodySlc := bodyStr[:]
var bodySlc []byte = make([]byte, 1024)

   bodyLen,readErr := req.Body.Read(bodySlc)
   if readErr == nil {
      fmt.Println("read body error"
) }else{ fmt.Println("the body has ",bodyLen," bytes") } fmt.Println("the body is:", string(bodySlc)) fmt.Println("the len of body ", len(bodySlc)) fmt.Fprintln(rsp, "hello" + req.URL.String()) //var str := string(bodySlc) 這裡直接使用Read方法讀出來的byte[],str中會有多餘的空格。str := byteString(bodySlc) fmt.Println
("the length of str is ", len(str)) var body2 ReqBody err := json.Unmarshal([]byte(str), &body2) if err != nil { fmt.Println(err.Error()) } else { fmt.Println("name:" + body2.Name) fmt.Println("name:" + body2.Body) fmt.Println("name:" + body2.Time) } }