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))

}

 

其他实例

package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}

 

posted @ 2021-11-27 14:42  JaydenQiu  阅读(41)  评论(0)    收藏  举报