Skip to content

Commit

Permalink
routing global Handler + logs
Browse files Browse the repository at this point in the history
  • Loading branch information
medilies committed Mar 15, 2023
1 parent d12157c commit b73af4a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
3 changes: 2 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ func main() {
defer db.Close()

mux := http.NewServeMux()
router.Router{}.RegisterRoutes(mux)
router.Router{}.Boot(mux)

fmt.Printf("Linstenning on, see: https://%s \n", appConfig.URL)

http.ListenAndServe(appConfig.URL, mux)
}
28 changes: 23 additions & 5 deletions internal/router/router.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package router

import (
"log"
"net/http"

"github.com/medilies/go-locate-em/internal/controllers"
Expand All @@ -11,12 +12,29 @@ type Router struct{}
var sc = &controllers.SearchController{}
var ac = &controllers.AreaController{}

func (Router) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/search", sc.Search)

mux.HandleFunc("/api/areas", ac.Index)
mux.HandleFunc("/api/areas/store", ac.Store)
func (Router) Boot(mux *http.ServeMux) {
mux.HandleFunc("/", routingHandler)

fs := http.FileServer(http.Dir("public"))
mux.Handle("/public/", http.StripPrefix("/public/", fs))
}

func routingHandler(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
method := r.Method

log.Println(" ", method, ": ", path)

// TODO: first check if route is handled
// TODO: make a list of routes [path, method, handler, middleware]

if path == "/api/search" {
sc.Search(w, r)
} else if path == "/api/areas" {
if method == http.MethodGet {
ac.Index(w, r)
} else if method == http.MethodPost {
ac.Store(w, r)
}
}
}
2 changes: 1 addition & 1 deletion public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
};

// send a POST request to the API with the GeoJSON data
fetch('https://127.0.0.1:8000/api/areas/store', {
fetch('https://127.0.0.1:8000/api/areas', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
Expand Down

0 comments on commit b73af4a

Please sign in to comment.