一, 服務端

package main

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

type User struct {
	ID   int    `json:"id"` // 字段標籤指定 JSON 鍵名
	Name string `json:"name"`
}

func handler4Test(resp http.ResponseWriter, req *http.Request) {
	switch req.Method {
	case "GET":
		resp.Write([]byte("Hello World Get"))
	case "POST":
		resp.Write([]byte("Hello World Post"))
		b, _ := io.ReadAll(req.Body)
		//resp.Write(b)
		var user User
		if err := json.Unmarshal(b, &user); err != nil {
			fmt.Println(err)
			resp.Write([]byte(err.Error()))
			return
		}
		resp.Write([]byte(user.Name))
	}
}

func handler4Login(resp http.ResponseWriter, req *http.Request) {

}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/test", handler4Test)
	mux.HandleFunc("/login", handler4Login)
	http.ListenAndServe(":8080", mux) //啓動服務
}

二,客户端

package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
)

func main() {
	client := new(http.Client)
	//req, _ := http.NewRequest("GET", "http://localhost:8080/test", nil)
	//res, _ := client.Do(req)
	//body := res.Body
	//b, _ := io.ReadAll(body)
	//fmt.Println(string(b))
	var params string = "{\n    \"id\": 123456,\n    \"name\": \"Kayer\"\n}"
	req, _ := http.NewRequest("POST", "http://localhost:8080/test", bytes.NewBuffer([]byte(params)))
	res, _ := client.Do(req)
	body := res.Body
	b, _ := io.ReadAll(body)
	fmt.Println(string(b))
}

三, 結果

Go之原生Http開發(基礎)_json