Skip to content

Instantly share code, notes, and snippets.

@crgimenes
Last active April 11, 2024 15:41
Show Gist options
  • Save crgimenes/92d851b944ca2e459da7daa5c44801bf to your computer and use it in GitHub Desktop.
Save crgimenes/92d851b944ca2e459da7daa5c44801bf to your computer and use it in GitHub Desktop.
string to io.ReadCloser
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)
}
@xiaoshude
Copy link

👍

@mlexs
Copy link

mlexs commented Jul 14, 2021

Awesome 👍

@yktoo
Copy link

yktoo commented Jul 27, 2021

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"))

@bernardolm
Copy link

👍

@crgimenes
Copy link
Author

Hello guys,
I updated the gist following your suggestions.
Thank you for your help!

@LemonNekoGH
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment