如果客户端POST表单数据则服务端可以直接调用Request的ParseForm()函数来获取对应参数和取值,而RESTful API接口POST的是JSON数据,服务端需要获取POST消息体的原始数据,方法如下:
server.go
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
func main() {
handler := func(w http.ResponseWriter, req *http.Request) {
b, e := ioutil.ReadAll(req.Body)
if e != nil {
fmt.Printf("%v\n", e)
} else {
fmt.Printf("%s\n", string(b))
}
io.WriteString(w, "OK\n")
}
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8889", nil))
}
client.go
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
url := "http://127.0.0.1:8889/"
data := []byte(`
{
"book":[
{
"id":"444",
"language":"C",
"edition":"First",
"author":"Dennis Ritchie "
},
{
"id":"555",
"language":"C++",
"edition":"second",
"author":" Bjarne Stroustrup "
}
]
}
`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
log.Fatal("Error reading request. ", err)
}
// Set client timeout
client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err != nil {
log.Fatal("Error reading response. ", err)
}
defer resp.Body.Close()
fmt.Println("response status:", resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading body. ", err)
}
fmt.Printf("response body:%s\n", body)
}
测试从客户端向服务端POST JSON数据:
服务端输出:
{
"book":[
{
"id":"444",
"language":"C",
"edition":"First",
"author":"Dennis Ritchie "
},
{
"id":"555",
"language":"C++",
"edition":"second",
"author":" Bjarne Stroustrup "
}
]
}
客户端输出:
response status: 200
response body:OK