From d889fbae51a43a40163c64cd0f6aabf9a4190e18 Mon Sep 17 00:00:00 2001 From: Inanc Gumus Date: Wed, 6 Nov 2019 12:28:26 +0300 Subject: [PATCH] refactor: io png detector ifaces --- interfaces/15-png-detector/main.go | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/interfaces/15-png-detector/main.go b/interfaces/15-png-detector/main.go index 646eb9a..c2c6927 100644 --- a/interfaces/15-png-detector/main.go +++ b/interfaces/15-png-detector/main.go @@ -23,12 +23,6 @@ import ( // go run . < rosie.unknown func main() { - const pngSign = "\x89PNG\r\n\x1a\n" - const pngSignLen = 8 - - // create an in-memory buffer (bytes.Buffer is an io.Reader and an io.Writer). - memory := bytes.Buffer{} - // get it from the web server resp, err := http.Get("https://inancgumus.github.com/x/rosie.unknown") if err != nil { @@ -36,10 +30,22 @@ func main() { } defer resp.Body.Close() + if err := transfer(resp.Body); err != nil { + log.Fatal(err) + } +} + +func transfer(r io.Reader) error { + const pngSign = "\x89PNG\r\n\x1a\n" + const pngSignLen = 8 + + // create an in-memory buffer (bytes.Buffer is an io.Reader and an io.Writer). + memory := bytes.Buffer{} + // stream from the web server to the in-memory buffer in 32KB data chunks. // resp.Body.Read(...) -> memory.Write(...) - if _, err := io.Copy(&memory, resp.Body); err != nil { - log.Fatal(err) + if _, err := io.Copy(&memory, r); err != nil { + return err } // get the accumulated bytes from the in-memory buffer. @@ -50,4 +56,6 @@ func main() { // compare it with the png signature. fmt.Printf("% x\n", pngSign) + + return nil }