教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go语言:RESTful API接口在服务端读取POST的JSON数据

Go语言:RESTful API接口在服务端读取POST的JSON数据

发布时间:2022-02-06   编辑:jiaochengji.com
教程集为您提供Go语言:RESTful API接口在服务端读取POST的JSON数据等资源,欢迎您收藏本站,我们将为您提供最新的Go语言:RESTful API接口在服务端读取POST的JSON数据资源

如果客户端POST表单数据则服务端可以直接调用Request的ParseForm()函数来获取对应参数和取值,而RESTful API接口POST的是JSON数据,服务端需要获取POST消息体的原始数据,方法如下:

server.go

<pre><code class="language-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)) } </code></pre>

client.go

<pre><code class="language-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) }</code></pre>

测试从客户端向服务端POST JSON数据:

服务端输出:

<pre><code> { "book":[ { "id":"444", "language":"C", "edition":"First", "author":"Dennis Ritchie " }, { "id":"555", "language":"C ", "edition":"second", "author":" Bjarne Stroustrup " } ] } </code></pre>

客户端输出:

<pre><code>response status: 200 response body:OK </code></pre>

 

到此这篇关于“Go语言:RESTful API接口在服务端读取POST的JSON数据”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Go语言:RESTful API接口在服务端读取POST的JSON数据
谈谈Go语言的Restful接口开发
Go Web编程--解析JSON请求和生成JSON响应
想系统学习GO语言(Golang
web API接口及restful规范详解
Go 语言实现 简单文件服务器支持RESTful API接口
Go语言爱好者周刊:第 78 期 — 这道关于 goroutine 的题
PHP写API输出的时用echo的原因
jquery post时content-type的几种取值
php项目中的接口怎么写

[关闭]
~ ~