GO学习笔记(10)-接口实现代码

2021-07-02  本文已影响0人  卡门001

通过这个例子会学习到

type ReceiverPoster interface {
    Receiver
    Poster
}
httputil.DumpResponse方法
http.get方法
panic(err)
defer resp.Body.Close()
...

程序结构

project
   mock/
      - mock.go
   real/
      - real.go
   - main.go

代码

project/mock/mock.go

package mock

type Receiver struct {
    Contents string
}

func (r Receiver) Get(url string) string {
    return r.Contents
}


project/real/real.go

package real

import (
    "net/http"
    "net/http/httputil"
    "time"
)

type Receiver struct {
    UserAgent string
    TimeOut time.Duration
}

func (r Receiver) Get(url string) string  {
    resp, err := http.Get(url)
    if err != nil{
        panic(err)
    }
    result,err := httputil.DumpResponse(resp,true)

    resp.Body.Close()

    if err != nil{
        panic(err)
    }
    return string(result)
}

project/main.go

package main

import (
    "carmen.com/study/receiver/mock"
    real2 "carmen.com/study/receiver/real"
    "fmt"
)

type Receiver interface {
    Get(url string) string
}

type Poster interface {
    Post(url string,form map[string]string) string
}

func download(r Receiver) string  {
    return r.Get("http://www.imooc.com")
}

func post(poster Poster)  {
    poster.Post("http://www.imooc.com", map[string]string{"name":"nian","course":"golang"})
}

type ReceiverPoster interface {
    Receiver
    Poster
}

func session(s ReceiverPoster)  {
    s.Post("http://www.imooc.com", map[string]string{"name":"nian","course":"golang"})
    s.Get("http://www.imooc.com")
}

func main() {
    var r Receiver
    r = mock.Receiver{"aa"}
    r = real2.Receiver{"www.imooc.com",0}

    var s ReceiverPoster
    s.Get("http://www.imooc.com")
    s.Post("http://www.imooc.com", map[string]string{"name":"nian","course":"golang"})
    fmt.Println(download(r))
}

上一篇 下一篇

猜你喜欢

热点阅读