From 592ca0bc22d6000ffc7316bfb06fa107cccc695a Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Wed, 19 Jun 2024 17:14:56 -0400 Subject: [PATCH] Dep injection --- .../dependency_injection/README.md | 4 +++ .../dependency_injection/go.mod | 3 +++ .../dependency_injection/greet.go | 27 +++++++++++++++++++ .../dependency_injection/greet_test.go | 19 +++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 learn_go_with_tests/dependency_injection/README.md create mode 100644 learn_go_with_tests/dependency_injection/go.mod create mode 100644 learn_go_with_tests/dependency_injection/greet.go create mode 100644 learn_go_with_tests/dependency_injection/greet_test.go diff --git a/learn_go_with_tests/dependency_injection/README.md b/learn_go_with_tests/dependency_injection/README.md new file mode 100644 index 0000000..cc2c39a --- /dev/null +++ b/learn_go_with_tests/dependency_injection/README.md @@ -0,0 +1,4 @@ +# Dependency Injection + +https://quii.gitbook.io/learn-go-with-tests/go-fundamentals/dependency-injection + diff --git a/learn_go_with_tests/dependency_injection/go.mod b/learn_go_with_tests/dependency_injection/go.mod new file mode 100644 index 0000000..d9b4671 --- /dev/null +++ b/learn_go_with_tests/dependency_injection/go.mod @@ -0,0 +1,3 @@ +module dependency_injection + +go 1.21.0 diff --git a/learn_go_with_tests/dependency_injection/greet.go b/learn_go_with_tests/dependency_injection/greet.go new file mode 100644 index 0000000..a10d9c6 --- /dev/null +++ b/learn_go_with_tests/dependency_injection/greet.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" +) + +func Greet(writer io.Writer, name string) { + fmt.Fprintf(writer, "Hello, %s\n", name) +} + +// func main() { +// Greet(os.Stdout, "Drew") +// } + +// Here you can see that since now our greeter function takes an object that +// implements the io.Writer interface we can now pass an object like the http.ResponseWriter +// to it. +func MyGreeterHandler(w http.ResponseWriter, r *http.Request) { + Greet(w, "world") +} + +func main() { + log.Fatal(http.ListenAndServe(":5001", http.HandlerFunc(MyGreeterHandler))) +} diff --git a/learn_go_with_tests/dependency_injection/greet_test.go b/learn_go_with_tests/dependency_injection/greet_test.go new file mode 100644 index 0000000..3da0b77 --- /dev/null +++ b/learn_go_with_tests/dependency_injection/greet_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "bytes" + "testing" +) + +func TestGreet(t *testing.T) { + // The Buffer type from the bytes package implements the Writer interface, because it has the method Write(p []byte) (n int, err error) + buffer := bytes.Buffer{} + Greet(&buffer, "Chris") + + got := buffer.String() + want := "Hello, Chris" + + if got != want { + t.Errorf("got %q want %q", got, want) + } +}