2 回答
TA贡献1802条经验 获得超5个赞
从中得到提示http.HandlerFunc,我可以想到以下内容
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
// ReadData reads data from an io.Reader
func ReadData(r io.Reader) {
buf := new(bytes.Buffer)
buf.ReadFrom(r)
s := buf.String()
fmt.Printf("read : %s \n", s)
}
// ReaderFunc takes a function and returns io.Reader
type ReaderFunc func([]byte) (int, error)
func (r ReaderFunc) Read(b []byte) (int, error) {
return r(b)
}
func main() {
// invoking ReadData with a regular io.Reader
r := strings.NewReader("data 123")
ReadData(r)
// invoking ReadData with an anonymous io.Reader
r = strings.NewReader("data 456")
ReadData(ReaderFunc(func(b []byte) (int, error) {
return r.Read(b)
}))
}
TA贡献1853条经验 获得超9个赞
一种方法是创建您自己的类型,将 aio.Reader和 a结合起来io.Closer并实现io.ReadCloser接口。是这样的:
type ReadCloseCombiner struct {
io.Reader
io.Closer
}
func (rcc ReadCloseCombiner) Read(p []byte) (n int, err error) {
return rcc.Reader.Read(p)
}
func (rcc ReadCloseCombiner) Close() error {
return rcc.Closer.Close()
}
并像这样使用它:
var file *os.File
file = ... // some File which needs to be closed
var reader io.Reader
reader = ... // get Reader from somewhere
var readCloser io.ReadCloser
readCloser = ReadCloseCombiner{reader, file}
// now pass readCloser around as needed
readCloser.Read(...)
readCloser.Close()
如果您想要更灵活的东西,我会考虑使用一种类型来代替读取和关闭函数,然后您可以将它传递给匿名函数(或者甚至reader.Read/file.Close在您的情况下)。
一种方法是创建您自己的类型,将 aio.Reader和 a结合起来io.Closer并实现io.ReadCloser接口。是这样的:
type ReadCloseCombiner struct {
io.Reader
io.Closer
}
func (rcc ReadCloseCombiner) Read(p []byte) (n int, err error) {
return rcc.Reader.Read(p)
}
func (rcc ReadCloseCombiner) Close() error {
return rcc.Closer.Close()
}
并像这样使用它:
var file *os.File
file = ... // some File which needs to be closed
var reader io.Reader
reader = ... // get Reader from somewhere
var readCloser io.ReadCloser
readCloser = ReadCloseCombiner{reader, file}
// now pass readCloser around as needed
readCloser.Read(...)
readCloser.Close()
如果您想要更灵活的东西,我会考虑使用一种类型来代替读取和关闭函数,然后您可以将它传递给匿名函数(或者甚至reader.Read/file.Close在您的情况下)。
- 2 回答
- 0 关注
- 105 浏览
添加回答
举报