Last active
April 11, 2024 15:41
-
-
Save crgimenes/92d851b944ca2e459da7daa5c44801bf to your computer and use it in GitHub Desktop.
string to io.ReadCloser
This file contains 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"))
๐
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
string
to[]byte
conversation better usestrings.NewReader()