NopCloser Wraps Reader Without Close
io.NopCloser satisfies io.ReadCloser for a bare io.Reader; Close is a no-op and the underlying reader keeps its position after reads.
Code
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)
}How the snippet works
Everything that executes sits inside the function main.
Caveats
- No install step: the snippet lives entirely inside the standard library.
Applying it
The signature doing the main work is func main()
The file’s steps are announced right in the output: first read:, close err:, second read:.
Statements that matter most here
payload := strings.NewReader("id=42&action=ping")
Interactive Tools for This Topic
FAQ
- What does NopCloser Wraps Reader Without Close print when run?
- Invoke the file as-is — the `first read:`, `close err:`, `second read:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.