duck typing
接口组合
type Retriever interface {
Get(url string) string
}
type Poster interface {
Post(url string,
form map[string]string) string
}
type session interface {
Poster
Retriever
}
func text(s session) string {
s.Post("www", map[string]string{
"contents": "dmt_csr",
})
return s.Get("www")
}
func main() {
s := &mock.Retriever{"what"}
fmt.Println(text(s))
}
package mock
type Retriever struct {
Contents string
}
func (r *Retriever) Get(url string) string {
return r.Contents
}
func (r *Retriever) Post(url string, form map[string]string) string {
r.Contents = form["contents"]
return "ok"
}
实现真正的get请求
import (
"net/http"
"net/http/httputil"
"time"
)
type Retriever struct {
UserAgent string
TimeOut time.Duration
}
func (r Retriever) Get(url string) string {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
res, err := httputil.DumpResponse(resp, true)
resp.Body.Close()
if err != nil {
panic(err)
}
return string(res)
}