2019-11-05 10:48:27 +03:00
|
|
|
// Copyright © 2018 Inanc Gumus
|
|
|
|
// Learn Go Programming Course
|
|
|
|
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
|
|
|
//
|
|
|
|
// For more tutorials : https://learngoprogramming.com
|
|
|
|
// In-person training : https://www.linkedin.com/in/inancgumus/
|
|
|
|
// Follow me on twitter: https://twitter.com/inancgumus
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2019-11-08 11:12:20 +03:00
|
|
|
"os"
|
2019-11-05 10:48:27 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
2019-11-06 13:47:13 +03:00
|
|
|
// initiate the transmission channel (http connection) to the webserver.
|
2019-11-05 10:48:27 +03:00
|
|
|
resp, err := http.Get("https://inancgumus.github.com/x/rosie.unknown")
|
|
|
|
if err != nil {
|
2019-11-08 11:12:20 +03:00
|
|
|
fmt.Fprintln(os.Stderr, err)
|
|
|
|
return
|
2019-11-05 10:48:27 +03:00
|
|
|
}
|
2019-11-08 11:12:20 +03:00
|
|
|
// close it so the http package can reuse the connection.
|
2019-11-05 10:48:27 +03:00
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2019-11-06 13:47:13 +03:00
|
|
|
// resp.Body here is an io.ReadCloser: Read() + Close() methods.
|
|
|
|
// but in the transfer function it's an io.Reader: Only the Read() method.
|
|
|
|
n, err := transfer(resp.Body)
|
|
|
|
if err != nil {
|
2019-11-08 11:12:20 +03:00
|
|
|
fmt.Fprintln(os.Stderr, err)
|
|
|
|
return
|
2019-11-06 12:28:26 +03:00
|
|
|
}
|
2019-11-06 13:47:13 +03:00
|
|
|
fmt.Printf("%d bytes transferred.\n", n)
|
|
|
|
|
|
|
|
// resp.Body.Close() runs here (because of the defer above)
|
2019-11-06 12:28:26 +03:00
|
|
|
}
|
|
|
|
|
2019-11-06 13:47:13 +03:00
|
|
|
func transfer(r io.Reader) (n int64, err error) {
|
2019-11-06 12:28:26 +03:00
|
|
|
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).
|
2019-11-06 13:47:13 +03:00
|
|
|
var memory bytes.Buffer
|
2019-11-06 12:28:26 +03:00
|
|
|
|
2019-11-06 13:47:13 +03:00
|
|
|
// stream from the standard input to the in-memory buffer in 32KB data chunks.
|
|
|
|
// r.Read(...) -> memory.Write(...)
|
|
|
|
if n, err = io.Copy(&memory, r); err != nil {
|
|
|
|
return n, err
|
2019-11-05 10:48:27 +03:00
|
|
|
}
|
|
|
|
|
2019-11-06 13:47:13 +03:00
|
|
|
// check the png signature.
|
2019-11-05 10:48:27 +03:00
|
|
|
buf := memory.Bytes()
|
|
|
|
fmt.Printf("% x\n", buf[:pngSignLen])
|
|
|
|
fmt.Printf("% x\n", pngSign)
|
2019-11-06 12:28:26 +03:00
|
|
|
|
2019-11-06 13:47:13 +03:00
|
|
|
return n, err
|
2019-11-05 10:48:27 +03:00
|
|
|
}
|