zoukankan      html  css  js  c++  java
  • 介绍 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
  • 相关阅读:
    MySQL 5.7.18 zip 文件安装过程
    Mysql 自定义随机字符串
    JAVA基本类型和引用类型
    初识JSP
    Java导出错误数据
    时序图的使用习惯
    Redis踩坑
    ES踩坑
    代码规范
    Git在公司的使用流程
  • 原文地址:https://www.cnblogs.com/wangjq19920210/p/13063842.html
Copyright © 2011-2022 走看看