mirror of
https://gitee.com/johng/gf
synced 2026-06-06 16:21:40 +08:00
improve DoRequestObj for gclient.Client
This commit is contained in:
@ -18,6 +18,7 @@ import (
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/gmeta"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
// DoRequestObj does HTTP request using standard request/response object.
|
||||
@ -81,13 +82,14 @@ func (c *Client) DoRequestObj(ctx context.Context, req, res interface{}) error {
|
||||
// /user/{name} -> /order/john
|
||||
func (c *Client) handlePathForObjRequest(path string, req interface{}) string {
|
||||
if gstr.Contains(path, "{") {
|
||||
requestParamsMap := gconv.MapStrStr(req)
|
||||
requestParamsMap := gconv.Map(req)
|
||||
if len(requestParamsMap) > 0 {
|
||||
path, _ = gregex.ReplaceStringFuncMatch(`\{(\w+)\}`, path, func(match []string) string {
|
||||
if v, ok := requestParamsMap[match[1]]; ok {
|
||||
return v
|
||||
foundKey, foundValue := gutil.MapPossibleItemByKey(requestParamsMap, match[1])
|
||||
if foundKey != "" {
|
||||
return gconv.String(foundValue)
|
||||
}
|
||||
return match[1]
|
||||
return match[0]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -27,7 +27,8 @@ func Test_Client_DoRequestObj(t *testing.T) {
|
||||
Id int
|
||||
}
|
||||
type UserQueryReq struct {
|
||||
g.Meta `path:"/user" method:"get"`
|
||||
g.Meta `path:"/user/{id}" method:"get"`
|
||||
Id int
|
||||
}
|
||||
type UserQueryRes struct {
|
||||
Id int
|
||||
@ -36,8 +37,8 @@ func Test_Client_DoRequestObj(t *testing.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.Group("/user", func(group *ghttp.RouterGroup) {
|
||||
group.GET("/", func(r *ghttp.Request) {
|
||||
r.Response.WriteJson(g.Map{"id": 1, "name": "john"})
|
||||
group.GET("/{id}", func(r *ghttp.Request) {
|
||||
r.Response.WriteJson(g.Map{"id": r.Get("id").Int(), "name": "john"})
|
||||
})
|
||||
group.POST("/", func(r *ghttp.Request) {
|
||||
r.Response.WriteJson(g.Map{"id": r.Get("Id")})
|
||||
@ -68,7 +69,9 @@ func Test_Client_DoRequestObj(t *testing.T) {
|
||||
client := g.Client().SetPrefix(url).ContentJson()
|
||||
var (
|
||||
queryRes *UserQueryRes
|
||||
queryReq = UserQueryReq{}
|
||||
queryReq = UserQueryReq{
|
||||
Id: 1,
|
||||
}
|
||||
)
|
||||
err := client.DoRequestObj(ctx, queryReq, &queryRes)
|
||||
t.AssertNil(err)
|
||||
|
||||
Reference in New Issue
Block a user