如何使用返回链接的方法为复杂的HTTP客户端编写接口



我正在编写一个软件包,该软件包需要将*gorequest.SuperAgent的实例传递给子弹中的方法

// main.go
func main() {
  req := gorequest.New()
  result := subpackage.Method(req)
  fmt.Println(result)
}
// subpackage.go
func Method(req *gorequest.SuperAgent) string {
  req.Get("http://www.foo.com").Set("bar", "baz")
  _, body, _ := req.End()
  return body
}

我一直在绕圈试图编写戈尔奎斯特超级代理的接口,以便我可以用 gorequest的存根正确隔离和测试我的子包方法。

type Getter Interface {
  Get(url string) Getter
  // In the previous Method, Get() returns a *gorequest.SuperAgent
  // which allows chaining of methods
  // Here I tried returning the interface itself
  // But I get a 'wrong type for Get method' error when passing a gorequest instance
  // have Get(string) *gorequest.SuperAgent
  // want Get(string) Getter
  End(callback ...func(response *gorequest.Response, body string, errs []error)) (*gorequest.Response, string, []error)
  // I have no idea how to handle the param and returned *gorequest.Response here
  // Put another interface ?
  // Tried replacing it with *http.Response but not quite understanding it
}
func Method(req Getter) string {
  ...
}

,您可以看到我在这里绊倒了几个点,无法找到一个很好的来源。任何指针都将不胜感激

除了定义Getter接口外,还可以定义围绕*gorequest.SuperAgent实现Getter接口的薄包装器。

type saGetter struct {
    sa *gorequest.SuperAgent
}
func (g *saGetter) Get(url string) Getter {
    g.sa = g.sa.Get(url)
    return g
}
func (g *saGetter) Set(param string, value string) Getter {
    g.sa = g.sa.Set(param, value)
    return g
}
func (g *saGetter) End(callback ...func(response *gorequest.Response, body string, errs []error)) (*gorequest.Response, string, []error) {
    return g.sa.End(callback...)
}

然后将您的Method定义为:

// subpackage.go
func Method(req Getter) string {
    req.Get("http://www.foo.com").Set("bar", "baz")
    _, body, _ := req.End()
    return body
}

您可以主要使用saGetter,例如:

// main.go
func main() {
    req := gorequest.New()
    result := subpackage.Method(&saGetter{req})
    fmt.Println(result)
}

然后嘲笑Getter用于测试Method实现很容易。

也就是说,我同意 @jimb的评论,即您可能不需要gorequest,并且使用net/http通常是更好的选择。

最新更新