实现说明
NopCloser 包装无 Close 的 Reader可以归结为函数 main。
使用要点
- 跑完文件,输出里会留下标记——
first read:、close err:、second read:。
常见问题
运行「NopCloser 包装无 Close 的 Reader」会打印什么?
运行文件本身,first read:、close err:、second read: 这些前缀各对应一段演示逻辑。
核心语句
payload := strings.NewReader("id=42&action=ping")
代码示例
package main
import (
"fmt"
"io"
"strings"
)
func main() {
payload := strings.NewReader("id=42&action=ping")
// interfaces that need an io.ReadCloser can wrap a plain io.Reader
var body io.ReadCloser = io.NopCloser(payload)
first, err := io.ReadAll(body)
fmt.Println("first read:", string(first), "err:", err)
fmt.Println("close err:", body.Close())
// NopCloser's Close is a no-op: the underlying reader is already at EOF
second, err := io.ReadAll(body)
fmt.Printf("second read: %q err: %v\n", second, err)
}