用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数据对象进行编码与解码的所有内容,欢迎小伙伴们交流讨论。

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...