HTTP客户端手动解析响应体数据

发布于:2024-05-16 ⋅ 阅读:(65) ⋅ 点赞:(0)

服务端

package main

import (
	"easyGo/person"
	"encoding/json"
	"net/http"
)

func main() {
	http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		p := &person.Person{
			Name: "jackie",
			Age:  30,
			T: person.T{
				S: "hello world!",
			},
		}

		resp := map[string]any{
			"status":  0,
			"message": "success",
			"data":    p,
		}

		jsonData, _ := json.Marshal(resp)

		_, _ = w.Write(jsonData)
	})

	if err := http.ListenAndServe(":9090", nil); err != nil {
		panic(err)
	}
}

客户端

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func parse(buf []byte) {
	var temp0 map[string]interface{} // Response

	err := json.Unmarshal(buf, &temp0)
	if err != nil {
		panic(err)
	}

	var temp1 = temp0["data"].(map[string]interface{})   // Person
	var temp2 = temp1["t"].(map[string]interface{})      // Person.T
	fmt.Println(temp1["name"], temp1["age"], temp2["s"]) // Person.T.S
}

func main() {
	url := "http://127.0.0.1:9090/test"

	resp, err := http.PostForm(url, nil)
	if err != nil {
		panic(err)
	}

	buf, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	parse(buf)
}

在这里插入图片描述