fmt.Printfprints to stdout, which is pretty hard for us to capture using the testing framework.
os.Stdout? What does
Fprintfexpect to get passed to it for the 1st argument?
Fprintfwhich expects an
Writerto send our greeting somewhere. Let's use this existing abstraction to make our code testable and more reusable.
Buffertype from the
bytespackage implements the
Writerinterface, because it has the method
Write(p byte) (n int, err error).
Writerand then we can check what was written to it after we invoke
Hello, Chris di_test.go:16: got '' want 'Hello, Chris'
fmt.Printfbut instead takes a
Writerto send the string to, whereas
fmt.Printfdefaults to stdout.
bytes.Buffer. This is technically correct but not very useful.
Greetfunction into a Go application where we want it to print to stdout.
./di.go:14:7: cannot use os.Stdout (type *os.File) as type *bytes.Buffer in argument to Greet
fmt.Fprintfallows you to pass in an
io.Writerwhich we know both
io.Writer? Just how general purpose is our
http.Requestthat was used to make the request. When you implement your server you write your response using the writer.
io.Writerso this is why we could re-use our
Greetfunction inside our handler.
io.Writerinterface we are able to use
bytes.Bufferin our test as our
Writerand then we can use other
Writers from the standard library to use our function in a command line app or in web server.