Go实战--net/http中JSON的使用(The way to go) - Go语言中文社区

Go实战--net/http中JSON的使用(The way to go)


生命不止,继续Go go go~~~

很显然,json广泛应用在客户端和服务端之间的数据交换。

之前介绍了go中的net/http package 和 encoding/json package,那我们今天就将二者结合,介绍一下在net/http的操作中如何使用JSON。

定义一个结构
包含了两个字段,id和balance:

type User struct{
    Id      string
    Balance uint64
}

通过POST或PUT或PATCH向服务端发送JSON

    u := User{Id: "110", Balance: 8}
    b := new(bytes.Buffer)
    json.NewEncoder(b).Encode(u)
    res, _ := http.Post("https://httpbin.org/post", "application/json; charset=utf-8", b)
    io.Copy(os.Stdout, res.Body)

其中,用到了encoding/json中的 NewEncoder 和 Encode, 用到了net/http中的 http.Post.
http.Post

func (c *Client) Post(url string, contentType string, body io.Reader) (resp *Response, err error)

在服务端解析JSON

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        var u User
        if r.Body == nil {
            http.Error(w, "Please send a request body", 400)
            return
        }
        err := json.NewDecoder(r.Body).Decode(&u)
        if err != nil {
            http.Error(w, err.Error(), 400)
            return
        }
        fmt.Println(u.Id)
    })
    log.Fatal(http.ListenAndServe(":8080", nil))

其中,用到了encoding/json中的 NewDecoder 和 Decode,用到了net/http中的 http.HandleFunc,用到了log中的 log.Fatal

构造服务端要返回的JSON

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        u := User{Id: "US123", Balance: 8}
        json.NewEncoder(w).Encode(u)
    })
    log.Fatal(http.ListenAndServe(":8080", nil))

解析服务端返回的JSON

    u := User{Id: "110 Balance: 8}
    b := new(bytes.Buffer)
    json.NewEncoder(b).Encode(u)
    res, _ := http.Post("https://httpbin.org/post", "application/json; charset=utf-8", b)
    var body struct {
        // httpbin.org sends back key/value pairs, no map[string][]string
        Headers map[string]string `json:"headers"`
        Origin  string            `json:"origin"`
    }
    json.NewDecoder(res.Body).Decode(&body)
    fmt.Println(body)

完整例子解析json数组

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {

    url := "https://api.xuebaclass.com/xuebaapi/v1/provinces"

    req, _ := http.NewRequest("GET", url, nil)

    req.Header.Add("accept", "application/json")
    req.Header.Add("content-type", "application/json")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)


    type Province struct {
        Id       int  `json:"id"`
        Province string `json:"province"`
    }
    provinces := make([]Province, 0)
    err := json.Unmarshal([]byte(body), &provinces)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Println(provinces)

}

输出:
[{1 北京} {2 上海} {3 天津} {4 重庆} {5 黑龙江} {6 吉林} {7 辽宁} {8 山东} {9 山西} {10 陕西} {11 河北} {12 河南} {13 湖北} {14 湖南} {15 海南} {16 江苏} {17 江西} {18 广东} {19 广西} {20 云南} {21 贵州} {22 四川} {23 内蒙古} {24 宁夏} {25 甘肃} {26 青海} {27 西藏} {28 新疆} {29 安徽} {30 浙江} {31 福建} {32 港澳台}]

这里写图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wangshubo1989/article/details/70245570
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 10:40:38
  • 阅读 ( 843 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢