Skip to content

Instantly share code, notes, and snippets.

@crgimenes
Last active April 11, 2024 15:41
Show Gist options
  • Star 45 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • 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)
}
@mr-linch
Copy link

To avoid string to []byte conversation better use strings.NewReader()

package main

import (
	"bytes"
        "strings"
	"fmt"
	"io/ioutil"
)

func main() {
	r := ioutil.NopCloser(strings.NewReader("hello world")) // r type is io.ReadCloser
	
	// example to test r
	buf := new(bytes.Buffer)
	buf.ReadFrom(r)
	r.Close()
	s := buf.String()
	fmt.Println(s)
}

@kfelter
Copy link

kfelter commented Jan 19, 2021

๐Ÿ‘

@mikeschinkel
Copy link

Perfect! Thanks for posting this.

@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