Dep injection
parent
5bd4222342
commit
592ca0bc22
@ -0,0 +1,4 @@
|
||||
# Dependency Injection
|
||||
|
||||
https://quii.gitbook.io/learn-go-with-tests/go-fundamentals/dependency-injection
|
||||
|
@ -0,0 +1,3 @@
|
||||
module dependency_injection
|
||||
|
||||
go 1.21.0
|
@ -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)))
|
||||
}
|
@ -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)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue