本文轉自https://freeaihub.com/article/decode-and-encode-json-in-go.html,該頁可在線進行實驗。
將演示如何使用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程序
cat >> json.go << EOF
// 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)
}
EOF
運行程序及開啟服務器進行驗證
go run json.go &
curl -s -XPOST -d '{"firstname":"Elon","lastname":"Mars","age":48}'
curl -s http://localhost/encode
總結
以上代碼及案例實操演示了如何使用Go語言中encoding/json
package使用