h5载服务器文件后获取,golang post json数据后服务器端获取不到内容?

碰到个灵异事件,我用golang的http库发送post请求,请求参数为json格式字符串,代码如下:

...

jsonParams := `{"name":"kazaff"}`

req, err := http.NewRequest("POST", url, strings.NewReader(jsonParams))

if err != nil {

panic(err)

}

req.Header.Set("Content-Type", "application/json;charset=UTF-8")

client := &http.Client{}

resp, err := client.Do(req)

if err != nil {

panic(err)

}

defer resp.Body.Close()

...

服务端同样使用golang来实现,解析客户端发送的请求后,一直报错,我打印出来log.Println(r.Body)后,发现是{}。。。

而我用postman提交相同的json数据给服务端,就可以获取正确的数据。蒙了,有哪位高手能指点一下小弟啊。

============

我补上服务端的代码:

...

router.HandleFunc("/",func(rep http.ResponseWriter, r *http.Request){

log.Println(r.Body)

defer r.Body.Close()

})

...

回答:

客户端:

package main

import (

"bytes"

"net/http"

"fmt"

)

func main() {

url := "xxxxxxxxxx"

jsonParams := `{"name":"kazaff"}`

req, err := http.NewRequest("POST", url, bytes.NewReader([]byte(jsonParams)))

if err != nil {

panic(err)

}

req.Header.Set("Content-Type", "application/json;charset=UTF-8")

client := &http.Client{}

resp, err := client.Do(req)

if err != nil {

panic(err)

}

defer resp.Body.Close()

fmt.Println("Response Status:", resp.Status)

}

建议使用bytes,另外strings也是可以的,我在服务端验证了一下范例的代码,OK

建议你把服务端的代码补充一下,方便做整体的判断

我在gin中用于测试的服务端部分代码:

buf := make([]byte, 1024)

n, _ := c.Request.Body.Read(buf)

fmt.Println(string(buf[0:n]))