1. 程式人生 > 其它 >1、介面定義

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