downloader.go:

    1. package main
    2. import (
    3. "fmt"
    4. "imooc.com/ccmouse/learngo/infra"
    5. "imooc.com/ccmouse/learngo/testing"
    6. )
    7. func getRetriever() retriever {
    8. return infra.Retriever{}
    9. // return testing.Retriever{}
    10. }
    11. // 接口
    12. type retriever interface {
    13. Get(string) string
    14. }
    15. func main() {
    16. var r retriever := getRetriever{}
    17. fmt.Println(r.Get("https://www.imooc.com"))
    18. }

    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"
    }