Last active
March 11, 2025 06:14
-
-
Save crgimenes/92d851b944ca2e459da7daa5c44801bf to your computer and use it in GitHub Desktop.
string to io.ReadCloser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bytes" | |
| "fmt" | |
| "io" | |
| "os" | |
| "strings" | |
| ) | |
| func main() { | |
| r := io.NopCloser(strings.NewReader("Hello, world!")) // r type is io.ReadCloser | |
| // example to test r | |
| buf := new(bytes.Buffer) | |
| n, err := buf.ReadFrom(r) | |
| if err != nil { | |
| fmt.Println(err) | |
| os.Exit(1) | |
| } | |
| r.Close() | |
| s := buf.String() | |
| fmt.Printf("%d bytes read, %q\r\n", n, s) | |
| } |
π
Perfect! Thanks for posting this.
π
Awesome π
Thanks a lot!
As ioutil is now deprecated, it's better to use a same-named method from io:
r := io.NopCloser(strings.NewReader("hello world"))π
Author
Hello guys,
I updated the gist following your suggestions.
Thank you for your help!
π
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To avoid
stringto[]byteconversation better usestrings.NewReader()