Skip to content

Instantly share code, notes, and snippets.

@dugancathal
Created August 20, 2017 02:10
Show Gist options
  • Save dugancathal/a6ecb741d3f437c3313947b33b389633 to your computer and use it in GitHub Desktop.
Save dugancathal/a6ecb741d3f437c3313947b33b389633 to your computer and use it in GitHub Desktop.
a sample of dependency injection in golang
package main
import (
"encoding/json"
"log"
"net/http"
)
// hashtag framework
type injectionContainer interface {
GetDep(name string) interface{}
}
type handler func(w http.ResponseWriter, r *http.Request) (int, http.Header, []byte)
type controller func(r *http.Request) (int, http.Header, []byte)
type injectable func(container injectionContainer) controller
func (c controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
code, headers, body := c(r)
for key, vals := range headers {
for _, val := range vals {
w.Header().Set(key, val)
}
}
w.WriteHeader(code)
w.Write(body)
}
// A default dependency injection container
type container map[string]interface{}
func (c container) GetDep(name string) interface{} {
return c[name]
}
// application code
type repo interface {
FindAll() []string
}
type movieRepo struct {
}
func (r *movieRepo) FindAll() []string {
return []string{}
}
func movieController(repo *movieRepo) controller {
return func(r *http.Request) (int, http.Header, []byte) {
movies := repo.FindAll()
body, _ := json.Marshal(movies)
return 200, http.Header{}, []byte(body)
}
}
func buildMovieController(container injectionContainer) http.Handler {
movieRepo := container.GetDep("movieRepo").(*movieRepo)
return http.Handler(movieController(movieRepo))
}
func main() {
c := injectionContainer(container{
"movieRepo": &movieRepo{},
})
http.Handle("/foo", buildMovieController(c))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment