通过这个例子会学习到
- 接口定义:type <名称> interface
- 结构体定义: type <名称> struct
- 接口组合
type ReceiverPoster interface {
Receiver
Poster
}
httputil.DumpResponse方法
http.get方法
panic(err)
defer resp.Body.Close()
...
- 规范的应用
- 每个目录可以是一个单独的包
- 包名和目录名保保持一致
- main包比较特色
- 首字母大写代码public,首字母小写代码私有变化
程序结构
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))
}
网友评论