Skip to content

Instantly share code, notes, and snippets.

@garukun
Created April 11, 2018 17:15
Show Gist options
  • Save garukun/07e940dcefd2a7f6d57edad6268c947b to your computer and use it in GitHub Desktop.
Save garukun/07e940dcefd2a7f6d57edad6268c947b to your computer and use it in GitHub Desktop.
dependency injection pattern
package main
import (
"net/http"
"net/http/httptest"
)
func main() {
m := mongo{}
h := handler{d: m}
http.ListenAndServe(":8080", h)
}
// package handler
type handler struct {
d handler_dal
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
type handler_dal interface {
Get(string) interface{}
}
type mockDal struct {
}
func (m mockDal) Get(string) interface{} {
return nil
}
// *_test.go
func TestSomething() {
//mdal := mockDal{/* mock */}
mmdal := daltest_MockDal{}
h := handler{d: mmdal}
httptest.NewServer(h)
// test
}
// package dal
type dal interface {
Get(string) interface{}
Store(string, string) error
}
// package dal/mongo
type mongo struct {
}
func (m mongo) Get(string) interface{} {
return nil
}
func (m mongo) Store(string, string) error {
return nil
}
// package dal/daltest
type daltest_MockDal struct {
}
func (m daltest_MockDal) Get(string) interface{} {
return nil
}
func (m daltest_MockDal) Store(string, string) error {
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment