实现真实的interface, 用来实现爬取百度的首页
package real
import (
"time"
"net/http"
"net/http/httputil"
)
type Retriever struct {
UserAgent string
TimeOut time.Duration//持续的
}
func (r Retriever) Get(url string) string{
resp, err := http.Get(url)
if err!=nil{
panic("http error")
}
result,err:=httputil.DumpResponse(resp, true)
resp.Body.Close()
if err!=nil{
panic("httputil dumpRespone ")
}
return string(result)
}
type Retriver interface {
//接口里面是一个函数,不用写func
Get(url string) string
}
func download(r Retriver) string{
return r.Get("http://www.baidu.com")
}
func main(){
var r Retriver
r = real.Retriever{}
fmt.Println(download(r))
}
有疑问加站长微信联系(非本文作者)