介绍 golang json数据的处理

原文链接:https://blog.csdn.net/weixin_43223076/article/details/83550229

demo1:

package main
import (
    "net/http"
    "log"
    "encoding/json"

)
type User struct{
    Id string
    Balance uint64

}
func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        u := User{Id: "www.361way.com", Balance: 8}
        json.NewEncoder(w).Encode(u)

    })
    log.Fatal(http.ListenAndServe(":8080", nil)
}

运行结果:

[root@localhost ~]# curl http://127.0.0.1:8080
{"Id":"www.361way.com","Balance":8}

 demo2:

package main

import (
    "net/http"
    "fmt"
    "log"
    "encoding/json"

)
type User struct{
    Id string
    Balance uint64

}
func main() {
    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))
}

运行结果:

curl http://127.0.0.1:8080 -d '{"Id": "https://www.linuxprobe.com", "Balance": 8}'

https://www.linuxprobe.com