Go网络编程-JSON

来自泡泡学习笔记
BrainBs讨论 | 贡献2024年2月7日 (三) 09:35的版本 (创建页面,内容为“ 这个例子将展示如何使用encoding/json包编码和解码JSON数据。 <syntaxhighlight lang="go">// 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.B…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

这个例子将展示如何使用encoding/json包编码和解码JSON数据。

// 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(":8080", nil)
}


$ go run json.go

$ curl -s -XPOST -d'{"firstname":"Elon","lastname":"Musk","age":48}' http://localhost:8080/decode
Elon Musk is 48 years old!

$ curl -s http://localhost:8080/encode
{"firstname":"John","lastname":"Doe","age":25}