downloader.go:
package mainimport ("fmt""imooc.com/ccmouse/learngo/infra""imooc.com/ccmouse/learngo/testing")func getRetriever() retriever {return infra.Retriever{}// return testing.Retriever{}}// 接口type retriever interface {Get(string) string}func main() {var r retriever := getRetriever{}fmt.Println(r.Get("https://www.imooc.com"))}
urlretriever.go:
package infra
import (
"fmt"
"io/ioutil"
"net/http"
)
type Retriever struct{}
func (Retriever) Get(url string) string {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
return string(bytes)
}
fakeretriever.go:
package testing
type Retriever struct{}
func (Retriever) Get(url string) string {
return "fake content"
}
