diff --git a/Caller.go b/Caller.go index f3d7a70..d074769 100644 --- a/Caller.go +++ b/Caller.go @@ -88,6 +88,22 @@ func (c *Caller) Head(app, path string, headers ...string) *gohttp.Result { return c.Do("HEAD", app, path, nil, headers...) } +// Call 发起通用的泛型请求并自动解析响应 +func Call[T any](method, app, path string, data any, headers ...string) (T, error) { + return CallT[T](DefaultDiscoverer.NewCaller(nil, nil), method, app, path, data, headers...) +} + +// CallT 发起泛型请求并自动解析响应 (由于 Go 方法不支持泛型,故使用函数) +func CallT[T any](c *Caller, method, app, path string, data any, headers ...string) (T, error) { + var result T + res := c.Do(method, app, path, data, headers...) + if res.Error != nil { + return result, res.Error + } + err := res.To(&result) + return result, err +} + // Do 发起通用请求 func (c *Caller) Do(method, app, path string, data any, headers ...string) *gohttp.Result { r, _ := c.DoWithNode(method, app, "", path, data, headers...) diff --git a/Discover.go b/Discover.go index aea8d64..b636d3c 100644 --- a/Discover.go +++ b/Discover.go @@ -129,6 +129,10 @@ func (d *Discoverer) Init() { SetConfig(conf) // 保持全局 Config 变量同步 } + if conf.App == "" { + conf.App = os.Getenv("DISCOVER_APP") + } + if conf.CallRetryTimes <= 0 { conf.CallRetryTimes = 10 } diff --git a/README.md b/README.md index a29bc56..98c2a3b 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ discover: ### 服务调用 (Caller) - `NewCaller(request *http.Request, logger *log.Logger) *Caller`: 创建调用器。传入原始请求可自动透传 Header。 +- `Call[T](method, app, path, data, headers...) (T, error)`: **[推荐]** 泛型快捷调用,自动解析 JSON 结果。 +- `CallT[T](caller, ...) (T, error)`: 针对指定调用器的泛型调用。 - `Caller.Get / Post / Put / Delete / Head`: 发起同步请求。 - `Caller.Do(method, app, path, data, headers...)`: 发起通用请求,返回 `http.Result`。 - `Caller.Open(app, path, headers...)`: 发起 WebSocket 连接。