客户端
package main import ( "c02_get_param/common" "fmt" "zdpgo_resty" ) func main() { // Create a Resty Client client := zdpgo_resty.New() // 设置字符串 resp, err := client.R(). SetHeader("Content-Type", "application/json"). SetBody(`{"username":"testuser", "password":"testpass"}`). // 设置请求 SetResult(&common.AuthSuccess{}). // 处理结果 Post("http://127.0.0.1:3333/") if err != nil { fmt.Println("err:", err) return } fmt.Println(resp.String()) // 设置字节 resp, err = client.R(). SetHeader("Content-Type", "application/json"). SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)). SetResult(&common.AuthSuccess{}). // or SetResult(AuthSuccess{}). Post("http://127.0.0.1:3333/") if err != nil { fmt.Println("err:", err) return } fmt.Println(resp.String()) // 设置结构体 resp, err = client.R(). SetBody(common.UserRequest{Username: "testuser", Password: "testpass"}). SetResult(&common.AuthSuccess{}). // or SetResult(AuthSuccess{}). SetError(&common.AuthSuccess{}). // or SetError(AuthError{}). Post("http://127.0.0.1:3333/") if err != nil { fmt.Println("err:", err) return } fmt.Println(resp.String()) }
请求对象
package common type UserRequest struct { Username string `json:"username"` Password string `json:"password"` }
响应对象
package common type AuthSuccess struct { Code int `json:"code"` Status bool `json:"status"` Message string `json:"message"` Data any `json:"data,omitempty"` }
服务端
package main import ( "c02_get_param/common" "encoding/json" "net/http" "zdpgo_chi" "zdpgo_chi/middleware" ) func main() { r := zdpgo_chi.NewRouter() r.Use(middleware.RequestID) r.Use(middleware.RealIP) r.Use(middleware.Logger) r.Use(middleware.Recoverer) r.Post("/", func(w http.ResponseWriter, r *http.Request) { // 获取查询参数 name := r.URL.Query().Get("name") age := r.URL.Query().Get("age") data := map[string]any{ "name": name, "age": age, } resp := common.AuthSuccess{ Code: 10000, Status: true, Message: "success", } // 获取请求头参数 data["authorization"] = r.Header.Get("Authorization") // 获取请求体参数 var req common.UserRequest json.NewDecoder(r.Body).Decode(&req) defer r.Body.Close() data["json"] = req // 返回JSON数据 resp.Data = data jsonData, err := json.Marshal(resp) if err != nil { w.Write([]byte(err.Error())) return } w.Write(jsonData) }) http.ListenAndServe(":3333", r) }
还没有评论,来说两句吧...