1、接口定义
作者:互联网
定义测试接口 testInterface/mock/main.go
package mock type Retriever struct { Contents string } // 给结构体添加方法 func (r Retriever) Get(url string) string { return r.Contents }
定义真实接口 testInterface/real/main.go
package real import ( "net/http" "net/http/httputil" "time" ) type Retriever struct { UserAgent string TimeOut time.Duration } func (r Retriever) Get(url string) string { res,err := http.Get(url) if err != nil { panic(err) } result,err := httputil.DumpResponse(res,true) if err != nil { panic(err) } // 读完 Response 的 body 后需要关掉 res.Body.Close() return string(result) }
正常使用 main.go
package main import ( "fmt" "testInterface/mock" "testInterface/real" ) // 定义接口 type Retriver interface { Get(url string) string } // 定义方法,调用接口 func download(r Retriver) string { return r.Get("https://baidu.com") } func main() { var r Retriver r = mock.Retriever{Contents: "this is a mock"} fmt.Println(download(r)) var newR Retriver newR = real.Retriever{} fmt.Println(download(newR)) }
标签:string,err,Get,接口定义,main,mock,Retriever 来源: https://www.cnblogs.com/mingliangge/p/15605616.html