Skip to content
6 changes: 5 additions & 1 deletion coolfacts/cmd/coolfacts_server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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))
}
}
Expand Down
30 changes: 6 additions & 24 deletions coolfacts/cmd/coolfacts_server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
25 changes: 25 additions & 0 deletions coolfacts/coolhttp/router.go
Original file line number Diff line number Diff line change
@@ -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
}