Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to convert [] byte to io.Reader in Go

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to convert [] byte into io.Reader in Go. It is very detailed and has a certain reference value. Friends who are interested must finish it!

I saw a problem on stackoverflow. The subject made a network request, and the API returned [] byte. What do you need to do if you want to convert it to io.Reader?

This problem is not complicated to solve, and it can be easily converted in a few lines of code. Not only that, it can also be converted back in reverse with a few lines of code.

Now listen to me slowly blow for you, first of all directly look at two pieces of code.

[] byte to io.Reader

Package mainimport ("bytes"fmt"log") func main () {data: = [] byte ("Hello AlwaysBeta") / / byte slice to bytes.Reader, which implements the io.Reader interface reader: = bytes.NewReader (data) / / read the data from reader buf: = make ([] byte, len (data) if _, err: = reader.Read (buf); err! = nil {log.Fatal (err)} fmt.Println (string (buf))}

Output:

Hello AlwaysBeta

This code first converts [] byte data into reader, then reads the data from reader and prints it out.

Io.Reader to [] byte

Package mainimport ("bytes"fmt"strings") func main () {ioReaderData: = strings.NewReader ("Hello AlwaysBeta") / / creates a bytes.Buffer and read from io.Reader buf: = & bytes.Buffer {} buf.ReadFrom (ioReaderData) / / retrieve a byte slice from bytes.Buffer data: = buf.Bytes () / / only read the left bytes from 6 fmt.Println (string (data [6:]))}

Output:

AlwaysBeta

This code first creates a reader, then reads the data to buf, and finally prints it out.

The above two pieces of code are the process of converting [] byte and io.Reader to each other. Comparing these two pieces of code, it is not difficult to find that there is a figure of NewReader. And in the conversion process, have played a key role.

So the question is, what on earth is this NewReader? Next, let's take a look at the source code.

Source code parsing

Go's io package provides the most basic IO interfaces, of which io.Reader and io.Writer are the most critical, and many native structures are developed around these two interfaces.

Let's talk about these two interfaces respectively:

Reader interface

Io.Reader represents a reader that reads data from a resource into the transport buffer. In a buffer, data can be streamed and used.

The API is defined as follows:

Type Reader interface {Read (p [] byte) (n int, err error)}

The Read () method reads len (p) bytes into p. It returns the number of bytes n read, as well as the error message when an error occurs.

To give an example:

Package mainimport ("fmt"io"os"strings") func main () {reader: = strings.NewReader ("Clear is better than clever") p: = make ([] byte, 4) for {n, err: = reader.Read (p) if err! = nil {if err = = io.EOF {fmt.Println ("EOF:", n) break} fmt.Println (err) os.Exit (1)} fmt.Println (n) String (p [: n])}}

Output:

4 Clea

4 r is

4 bet

4 ter

4 than

4 cle

3 ver

EOF: 0

This code constantly reads data from reader, reading 4 bytes at a time, and then prints it out until the end.

The last returned n value may be less than the buffer size.

Writer interface

Io.Writer represents a writer that reads data from the buffer and writes it to the target resource.

Type Writer interface {Write (p [] byte) (n int, err error)}

The Write method writes len (p) bytes from p to the object data stream. It returns the number of bytes written from p, as well as the error message returned when an error occurs.

To give an example:

Package mainimport ("bytes"fmt"os") func main () {/ / create Buffer staging space And write a string to Buffer / / write a string to var buf bytes.Buffer buf.Write ([] byte ("hello world,")) / / use Fprintf to concatenate a string into Buffer fmt.Fprintf (& buf, "welcome to golang!") / / output the contents of Buffer to the standard output device buf.WriteTo (os.Stdout)}

Output:

Hello world, welcome to golang!

Bytes.Buffer is a struct type that temporarily stores written data and implements the Write method of the io.Writer interface.

The WriteTo method definition:

Func (b * Buffer) WriteTo (w io.Writer) (n int64, err error)

The first parameter of the WriteTo method is the io.Writer interface type.

Conversion principle

Let's go back to the conversion at the beginning of the article.

As long as an instance implements the method Read () in interface io.Reader, interface io.Reader is satisfied.

Both the bytes and strings packages implement the Read () method.

/ / src/bytes/reader.go// NewReader returns a new Reader reading from b.func NewReader (b [] byte) * Reader {return & Reader {b, 0,-1}} / / src/strings/reader.go// NewReader returns a new Reader reading from s.Accord / It is similar to bytes.NewBufferString but more efficient and read-only.func NewReader (s string) * Reader {return & Reader {s, 0,-1}}

When NewReader is called, the corresponding T.Reader types are returned, and they are all extended by io.Reader, so the transformation is implemented.

The above is all the content of the article "how to convert [] byte to io.Reader in Go". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report