本次练习包含以下三个文件:
主函数代码:
package main
import (
"2/testing"
"fmt"
)
//读取网页html
//func main() {
// resp, err := http.Get("https://www.imooc.com")
// if err != nil {
// panic(err)
// }
// defer resp.Body.Close()
// bytes, _ := ioutil.ReadAll(resp.Body)
// fmt.Printf("%s", bytes)
//}
//封装成函数
//func retrieve(url string) []byte {
// resp, err := http.Get(url)
// if err != nil {
// panic(err)
// }
// defer resp.Body.Close()
// bytes, _ := ioutil.ReadAll(resp.Body)
// return bytes
//}
//go语言的接口练习
func getRetriever() retriever {
return testing.Retriever{}
}
type retriever interface {
Get(string) string
}
func main() {
var r retriever = getRetriever()
fmt.Println(r.Get(
"https://www.imooc.com"))
}
infra文件夹下代码
package infra
import (
"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)
}
testing文件夹下代码:
package testing
type Retriever struct{}
func (Retriever) Get(url string) string {
return "fake news!"
}
接口封装调用testing文件夹下的函数:
//go语言的接口练习
func getRetriever() retriever {
return testing.Retriever{}
}
type retriever interface {
Get(string) string
}
func main() {
var r retriever = getRetriever()
fmt.Println(r.Get(
"https://www.imooc.com"))
}
练习结果: