Analysis of Golang IO package

Analysis of Golang IO package

io package provides I / O primitives (not primitives or) of the basic interface. io package defines four basic interfaces Reader, Writer, Closer, Seeker for representing binary stream read, write, and close operations addressing. These primitives are packaged and interfaces to the underlying operations, so as no special instructions, these primitives and interfaces is not to be regarded as thread-safe.

Reader

Reader interface package Read the basic method. Read read length len (p) bytes of data, and written to p. Reads return results containing (0 <= n <= len (p)) and error information data bytes.

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

When reading Read n> EOF after experiencing abnormal or 0 bytes, Read returns the number of bytes read. When reading this, you may return a non-null error. But once again read, will read empty and return error. Typical examples are, Reader reads the input stream section completely, the next Read returns 0, EOF:

func main() {
    r := strings.NewReader("some io.Reader stream to be read")

    b := make([]byte, 32)
    n, err := r.Read(b)
    // 32, some io.Reader stream to be read, <nil>
    fmt.Printf("%d, %s, %v", n, b, err)

    b = make([]byte, 32)
    n, err = r.Read(b) 
    // 0, EOF
    fmt.Printf("%d, %v", n, err)
}

Read implementation method is not recommended return 0 at the same time, returns nil error, unless len (p) == 0. It does not mean EOF.

Reader interface commonly used are:

Reader type in 1.strings package

Related support functions are:

  • func NewReader (s string) * Reader: production string s corresponding Reader (Read-only, the Write method is not implemented)
  • func (r * Reader) Len () int: the number of bytes in the string section have not been read
  • unc (r * Reader) Read (b [] byte) (n int, err error): Read-implemented method

Buffer type and type in 2.bytes package Reader

Buffer type different from the type of Reader and that the former Writer implements an interface, which is read-only.

Writer

Writer Interface encapsulates the Write method. Len achieve data fetch (p) from the buffer size in bytes, is written the underlying data stream. If all goes well, Write byte size written back (n == len (p)) and nil error. Otherwise non-nil error and n <len (p).

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

Writer common interface are:

Builder packet type in 1.strings

Builder for efficiently string formation, minimize consumption of memory resources.

func main() {
    proverbs := []string{
        "Channels orchestrate mutexes serialize.",
        "Cgo is not Go.",
        "Errors are values.",
        "Don't panic.",
    }
    var writer strings.Builder

    for _, p := range proverbs {
        n, err := writer.Write([]byte(p))
        if err != nil {
            fmt.Println(err)
        }
        if n != len(p) {
            fmt.Println("failed to write data")
        }
    }

    // 打印 Channels orchestrate mutexes serialize.Cgo is not Go.Errors are values.Don't panic.
    fmt.Println(writer.String())
}

Buffer type in 2.bytes package

ResponseWriter packet interface in 3.http

type ResponseWriter interface {
    // 返回 Header 对象,可以通过它的 Set() 方法设置头部
    Header() Header

    // 写入数据到 HTTP 应答报文
    Write([]byte) (int, error)

    // 设置返回状态码。如果没有调用这个函数,默认设置为 http.StatusOK
    WriteHeader(statusCode int)
}

The following examples localhost: 8080 / handler listens for requests, and written back to the string "This is the HTTP response."

func main() {
    http.HandleFunc("/handler", func(w http.ResponseWriter, req *http.Request) {
        io.WriteString(w, "This is the HTTP response.\n")
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

A Response packet in 4.go-restful

Response type encapsulates http.ResponseWriter, it provides a convenient way to support a lot of write-back data.

type Response struct {
    http.ResponseWriter
    // contains filtered or unexported fields
}

Closer

Closer interface package Close method. Is generally used to close the file, close the channel, the connection is closed, closing a database

type Closer interface {
    Close() error
}

Seeker

Seeker Seeker interface package method. Seek method for setting an offset (offset), the next write operation begins with the start position of a particular data stream. And ReaderAt, WriteAt interfaces somewhat similar, but more flexible Seeker interfaces, can better control the position of the read and write data stream.

type Seeker interface {
    Seek(offset int64, whence int) (int64, error)
}

Interpretation offset offset depends whence (= from where, from there). It represents 0 relative to the starting position, 1 indicates an offset relative to the current, while at the opposite end thereof. 2. The following example, the pointer will move to the bottom fifth position from the right characters. So reader.Len () will output 5.

func main() {
    reader := strings.NewReader("This is a test")
    reader.Seek(-5, io.SeekEnd)
    fmt.Printf("The unread portion of the string: %d\n", reader.Len())
}

Primitive combination

By combining four basic interfaces of the above, we can get a variety of primitive combinations, such as: ReadWriter, ReadCloser, WriteCloser and so on.

type ReadWriter interface {
    Reader
    Writer
}

Reference documents:

golang io interpretation in io.go

Guess you like

Origin www.cnblogs.com/guangze/p/11595143.html