用Go语言建立http-server响应对JSON数据对象进行编码与解码

摘要

本文将演示如何使用Go语言中encoding/json package,结合建立一台http-server响应对JSON数据对象进行编码与解码的操作。

JSON简介:因为XML整合到HTML中各个浏览器实现的细节不尽相同,Douglas Crockford和 Chip Morningstar一起从JS的数据类型中提取了一个子集,作为新的数据交换格式,因为主流的浏览器使用了通用的JavaScript引擎组件,所以在解析这种新数据格式时就不存在兼容性问题,于是他们将这种数据格式命名为 “JavaScript Object Notation”,缩写为 JSON。来自:新消息频道

正文

配置Go语言运行环境

cp /share/tar/go1.12.9.linux-amd64.tar.gz .
 
tar -C /usr/local -xzvf go1.12.9.linux-amd64.tar.gz
 
echo export PATH=$PATH:/usr/local/go/bin >> /etc/profile
 
source /etc/profile
 
go version

编写Go语言http server程序

#使用vim创建json.go文件,内容如下
package main
 
import (
    "encoding/json"
    "fmt"
    "net/http"
)
 
type User struct {
    Firstname string `json:"firstname"`
    Lastname  string `json:"lastname"`
    Age       int    `json:"age"`
}
 
func main() {
    http.HandleFunc("/decode", func(w http.ResponseWriter, r *http.Request) {
        var user User
        json.NewDecoder(r.Body).Decode(&user)
 
        fmt.Fprintf(w, "%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
    })
 
    http.HandleFunc("/encode", func(w http.ResponseWriter, r *http.Request) {
        peter := User{
            Firstname: "John",
            Lastname:  "Doe",
            Age:       25,
        }
 
        json.NewEncoder(w).Encode(peter)
    })
 
    http.ListenAndServe(":80", nil)
}

运行程序及开启服务器进行验证

go run json.go &
curl -s -X POST -d '{"firstname":"Elon","lastname":"Mars","age":48}' http://localhost/decode
curl -s http://localhost/encode

完结

以上就是用Go语言建立http-server响应对JSON数据对象进行编码与解码的所有内容,欢迎小伙伴们交流讨论。

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...