簡體   English   中英

Go:將數據從 io.Reader 復制到 io.Writer 實現與睡眠超時,空寫入

[英]Go: Copy data from io.Reader to io.Writer implementations with sleep timeout, empty Writes

我正在嘗試將數據從 io.Reader 實現復制到 io.Writer 實現,並在下一次迭代之前延遲(time.Sleep)。 理想情況下,我想控制該過程(即 io.Copy 並不理想,因為我可能想在讀取和寫入之間執行一些操作)。

無論如何,在下面的代碼中嘗試了 4 種方法,它應該在go.dev/play中運行。 除了空字符串之外,我無法獲得任何寫入任何內容的方法,盡管所有寫入方法確實報告了正確的寫入字節數(與讀取報告的相同)。 我可能缺少一些基本的東西,但任何幫助/解釋都非常感謝,因為我很困惑。

以下代碼包含 4 種不同方法的注釋和函數,用於在下一次迭代之前以指定的延遲 (time.Sleep) 從 io.Reader 的自定義實現到 io.Writer 復制和記錄數據。 您可以在下方評論/取消評論所需的 function 以觀察結果。

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "math/rand"
    "time"
)

// READ
type MyReader struct{}

func (r *MyReader) Read(p []byte) (read int, err error) {

    someString := fmt.Sprintf("testing-%d", rand.Int())

    p = []byte(someString)
    read = len(p)

    log.Printf("io read %d bytes: %s\n", read, string(p))

    return read, io.EOF
}

// WRITE
type MyWriter struct{}

func (w *MyWriter) Write(p []byte) (wrote int, err error) {

    wrote = len(p)
    log.Printf("io wrote %d bytes: %s\n", wrote, string(p))

    return
}

// MAIN
func main() {

    // The following contains comments and functions for 4 different approaches to copying and logging data from
    // custom implementations of io.Reader to an io.Writer with a specified delay (time.Sleep) before the next
    // iteration. You may comment/uncomment the desired function below to observe the results.

    // AutoIoCopy - Approach 1) io.Copy
    //
    // Expected is to read and log the correct value (generated in the method)
    // then write the value (output another log)
    //
    // Actual is that the bufio.Write method is called and the MyWriter.Write method of the io.Writer implementation
    // is executed, but the output logged by MyWriter.Write is empty instead of the expected string reported by the
    // MyReader.Read log.
    //
    AutoIoCopy()

    // ReadBytesApproach - Approach 2) Using ReadBytes('\n')
    //
    // Expected is to read and log the correct value (generated in the method)
    // then write the value (output another log)
    //
    // Actual is that the bufio.Write method is called and reports written bytes, but the Write method of MyWriter
    // io.Writer implementation is never executed, it is skipped and another Read occurs
    //
    //ReadBytesApproach()

    // ReadLineApproach - Approach 3) Using ReadLine()
    //
    // Expected is to read and log the correct value (generated in the method)
    // then write the value (output another log)
    //
    // Actual is that the bufio.Write method is called and reports written bytes, but the Write method of MyWriter
    // io.Writer implementation is never executed, it is skipped and another Read occurs
    //
    //ReadLineApproach()

    // WriteToApproach - Approach 4) Using WriteTo()
    //
    // Expected is to read and log the correct value (generated in the method)
    // then write the value (output another log)
    //
    // Actual is that the bufio.Write method is called and reports written bytes, but the Write method of MyWriter
    // io.Writer implementation is never executed, it is skipped and another Read occurs
    //
    //WriteToApproach()

}

// Approaches:

// AutoIoCopy - Approach 1) io.Copy
//
// Expected is to read and log the correct value (generated in the method)
// then write the value (output another log)
//
// Actual is that the bufio.Write method is called and the MyWriter.Write method of the io.Writer implementation
// is executed, but the output logged by MyWriter.Write is empty instead of the expected string reported by the
// MyReader.Read log.
//
func AutoIoCopy() {

    reader := MyReader{}
    writer := MyWriter{}

    for {
        _, _ = io.Copy(&writer, &reader)
        time.Sleep(1000 * time.Millisecond)
    }
}

// ReadBytesApproach - Approach 2) Using ReadBytes('\n')
//
// Expected is to read and log the correct value (generated in the method)
// then write the value (output another log)
//
// Actual is that the bufio.Write method is called but the Write method of MyWriter io.Writer implementation
// is never executed, it is skipped and another Read occurs
//
func ReadBytesApproach() {

    reader := MyReader{}
    writer := MyWriter{}

    bufRead := bufio.NewReader(&reader)
    bufWrite := bufio.NewWriter(&writer)

    for {

        // Using ReadBytes('\n')
        readBytes, err := bufRead.ReadBytes('\n')

        if err != nil {

            switch err {
            case io.EOF:

                log.Printf("io.EOF detected\n")
                wrote, err := bufWrite.Write(readBytes)
                if err != nil {
                    log.Printf("error writing: %s\n", err)
                }
                convertedValue := string(readBytes)
                log.Printf("bufio wrote %d bytes: %s\n", wrote, convertedValue)
                break

            default:
                log.Printf("bufio error reading: %s\n", err.Error())
                break
            }

        } else {
            log.Printf("no error, continue to read\n")
        }

        time.Sleep(1000 * time.Millisecond)
    }
}

// ReadLineApproach - Approach 3) Using ReadLine()
//
// Expected is to read and log the correct value (generated in the method)
// then write the value (output another log)
//
// Actual is that the bufio.Write method is called but the Write method of MyWriter io.Writer implementation
// is never executed, it is skipped and another Read occurs
//
func ReadLineApproach() {

    reader := MyReader{}
    writer := MyWriter{}

    bufRead := bufio.NewReader(&reader)
    bufWrite := bufio.NewWriter(&writer)

    for {

        // Using ReadLine()
        readBytes, _, err := bufRead.ReadLine()

        if err != nil {

            switch err {
            case io.EOF:

                log.Printf("io.EOF detected\n")
                wrote, err := bufWrite.Write(readBytes)
                if err != nil {
                    log.Printf("error writing: %s\n", err)
                }
                convertedValue := string(readBytes)
                log.Printf("bufio wrote %d bytes: %s\n", wrote, convertedValue)
                break

            default:
                log.Printf("bufio error reading: %s\n", err.Error())
                break
            }

        } else {
            log.Printf("no error, continue to read\n")
        }

        time.Sleep(1000 * time.Millisecond)
    }

}

// WriteToApproach - Approach 4) Using WriteTo()
//
// Expected is to read and log the correct value (generated in the method)
// then write the value (output another log)
//
// Actual is that neither the bufio.Write or the Write method of MyWriter io.Writer implementation is executed,
// it is skipped and another Read occurs
//
func WriteToApproach() {

    reader := MyReader{}
    writer := MyWriter{}

    bufRead := bufio.NewReader(&reader)
    bufWrite := bufio.NewWriter(&writer)

    for {
        wrote, _ := bufRead.WriteTo(bufWrite)
        log.Printf("bufio wrote %d bytes\n", wrote)
        time.Sleep(1000 * time.Millisecond)
    }
}

問題出在MyReader.Read方法中

p = []byte(someString)

應該

read = copy(p, someString)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM