标签:接口 http data www defer struct ring int txt
图片来源 https://medium.com/learning-the-go-programming-language/streaming-io-in-go-d93507931185
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
package main
import (
"io"
"net/http"
"os"
"strings"
)
type R struct {
reader io.Reader
}
func NewReader(r io.Reader) *R {
return &R{
reader: r,
}
}
func (r *R) Read(p []byte) (n int, err error) {
if _, err = r.reader.Read(p); err != nil {
return
}
return len(p), nil
}
func main() {
netR, err := http.Get("https://www.bilibili.com/")
if err != nil {
panic(err)
}
defer netR.Body.Close()
fileR, err := os.Open("/tmp/data.txt")
if err != nil {
panic(err)
}
//读内存
r1 := NewReader(strings.NewReader(""))
b := make([]byte, 10*1024)
if _, err := r1.Read(b); err != nil {
panic(err)
}
//读网络
r2 := NewReader(netR.Body)
if _, err := r2.Read(b); err != nil {
panic(err)
}
//读文件
r3 := NewReader(fileR)
if _, err := r3.Read(b); err != nil {
panic(err)
}
}
标签:接口 http data www defer struct ring int txt
原文地址:https://www.cnblogs.com/alin-qu/p/10225268.html