golang json数据的处理
使用golang下的net/http模块,可以很容易的实现webserver功能。本篇就结合http模块在POST发送josn数据给webserver以及webserver在收到json数据后如何处理。
一、server端处理json数据
server端代码如下:
1package main
2 import (
3 "net/http"
4 "fmt"
5 "log"
6 "encoding/json"
7 )
8 type User struct{
9 Id string
10 Balance uint64
11 }
12func main() {
13 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
14 var u User
15 if r.Body == nil {
16 http.Error(w, "Please send a request body", 400)
17 return
18 }
19 err := json.NewDecoder(r.Body).Decode(&u)
20 if err != nil {
21 http.Error(w, err.Error(), 400)
22 return
23 }
24 fmt.Println(u.Id)
25 })
26 log.Fatal(http.ListenAndServe(":8080", nil))
27}
通过go run server.go运行后,可以通过curl 命令进行测试:
1curl http://127.0.0.1:8080 -d '{"Id": "www.361way.com", "Balance": 8}'
通过curl命令执行后,在server端屏幕上能正常打印www.361way.com就表示server端已正常处理json数据。
二、client端的json post处理
client端实现的功能就是上面curl命令执行实现的功能,其代码如下:
1package main
2 import (
3 "net/http"
4 "encoding/json"
5 "io"
6 "os"
7 "bytes"
8 )
9type User struct{
10 Id string
11 Balance uint64
12}
13func main() {
14 u := User{Id: "www.361way.com", Balance: 8}
15 b := new(bytes.Buffer)
16 json.NewEncoder(b).Encode(u)
17 res, _ := http.Post("http://127.0.0.1:8080", "application/json; charset=utf-8", b)
18 io.Copy(os.Stdout, res.Body)
19}
三、服务端返回json数据
避免可能描述的歧义,这里用英文描述为“Encoding JSON in a server response”,即通过服务器处理后,将json数据返回给客户端
1package main
2 import (
3 "net/http"
4 "log"
5 "encoding/json"
6 )
7 type User struct{
8 Id string
9 Balance uint64
10 }
11func main() {
12 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
13 u := User{Id: "www.361way.com", Balance: 8}
14 json.NewEncoder(w).Encode(u)
15 })
16 log.Fatal(http.ListenAndServe(":8080", nil))
17}
通过curl http://127.0.0.1:8080 其会返回{Id: “www.361way.com”, Balance: 8}数据给客户端。
四、返回响应头信息
在向服务端发送数据后,有时我们需要获取响应头的信息,可以通过如下代码处理:
1package main
2 import (
3 "net/http"
4 "encoding/json"
5 "bytes"
6 "fmt"
7 )
8type User struct{
9 Id string
10 Balance uint64
11}
12func main() {
13 u := User{Id: "www.361way.com", Balance: 8}
14 b := new(bytes.Buffer)
15 json.NewEncoder(b).Encode(u)
16 res, _ := http.Post("https://httpbin.org/post", "application/json; charset=utf-8", b)
17 var body struct {
18 //sends back key/value pairs, no map[string][]string
19 Headers map[string]string `json:"headers"`
20 Origin string `json:"origin"`
21 }
22 json.NewDecoder(res.Body).Decode(&body)
23 fmt.Println(body)
24}
以上代码在向httpbin.org post数据后,会得到如下响应信息:
1{map[Content-Length:36 Content-Type:application/json; charset=utf-8 Host:httpbin.org User-Agent:Go-http-client/1.1 Accept-Encoding:gzip Connection:close] 115.28.174.118}
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/go-http-json/5794.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.