diff --git a/coolfacts/cmd/coolfacts_server/main.go b/coolfacts/cmd/coolfacts_server/main.go index a5be929..24ac813 100644 --- a/coolfacts/cmd/coolfacts_server/main.go +++ b/coolfacts/cmd/coolfacts_server/main.go @@ -7,6 +7,7 @@ import ( "time" "github.com/FTBpro/go-workshop/coolfacts/coolfact" + "github.com/FTBpro/go-workshop/coolfacts/coolhttp" "github.com/FTBpro/go-workshop/coolfacts/inmem" ) @@ -16,10 +17,13 @@ func main() { factsRepo := inmem.NewFactsRepository(seedFacts()...) service := coolfact.NewService(factsRepo) server := NewServer(service) + router := coolhttp.NewRouter() + router.SetNotFoundHandler(server.HandleNotFound) + server.RegisterRouter(router) log.Println("starting server on port 9002") log.Println("You can go to http://127.0.0.1:9002/ping") - if err := http.ListenAndServe(":9002", server); err != nil { + if err := http.ListenAndServe(":9002", router); err != nil { panic(fmt.Errorf("server crashed! err: %w", err)) } } diff --git a/coolfacts/cmd/coolfacts_server/server.go b/coolfacts/cmd/coolfacts_server/server.go index efa77de..4f38a94 100644 --- a/coolfacts/cmd/coolfacts_server/server.go +++ b/coolfacts/cmd/coolfacts_server/server.go @@ -6,12 +6,15 @@ import ( "log" "net/http" "strconv" - "strings" "time" "github.com/FTBpro/go-workshop/coolfacts/coolfact" ) +type Router interface { + Handle(method, path string, handler http.HandlerFunc) +} + type FactsService interface { GetFacts(filters coolfact.Filters) ([]coolfact.Fact, error) CreateFact(fact coolfact.Fact) error @@ -40,29 +43,8 @@ func NewServer(factsService FactsService) *server { } } -func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - log.Println("incoming request", r.Method, r.URL.Path) - - switch r.Method { - case http.MethodGet: - switch strings.ToLower(r.URL.Path) { - case "/ping": - s.HandlePing(w, r) - case "/facts": - s.HandleGetFacts(w, r) - default: - s.HandleNotFound(w, r) - } - case http.MethodPost: - switch strings.ToLower(r.URL.Path) { - case "/facts": - s.HandleCreateFact(w, r) - default: - s.HandleNotFound(w, r) - } - default: - s.HandleNotFound(w, r) - } +func (s *server) RegisterRouter(router Router) { + // TODO: implement } func (s *server) HandlePing(w http.ResponseWriter, _ *http.Request) { diff --git a/coolfacts/coolhttp/router.go b/coolfacts/coolhttp/router.go new file mode 100644 index 0000000..d81cae6 --- /dev/null +++ b/coolfacts/coolhttp/router.go @@ -0,0 +1,25 @@ +package coolhttp + +import ( + "net/http" +) + +type router struct { + notFoundHandler http.HandlerFunc +} + +func NewRouter() *router { + return &router{} +} + +func (r *router) SetNotFoundHandler(handler http.HandlerFunc) { + r.notFoundHandler = handler +} + +func (r *router) Handle(method, path string, handler http.HandlerFunc) { + // TODO: implement +} + +func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) { + // TODO: implement +}