Skip to content

Commit

Permalink
try gracefull shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
Dima committed Nov 4, 2023
1 parent 44697ff commit 99e508d
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions backend/api/router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package api

import (
"log"
"net/http"
"ytstalker/backend/youtube"

"html/template"

"github.com/gorilla/mux"
"zombiezen.com/go/sqlite/sqlitex"
)

var templates = template.Must(template.ParseGlob("frontend/*/*.html"))

type Router struct {
mux.Router
db *sqlitex.Pool
ytr *youtube.YouTubeRequester
}

func NewRouter(db *sqlitex.Pool, ytr *youtube.YouTubeRequester) *Router {

router := &Router{
Router: *mux.NewRouter(),
db: db,
ytr: ytr,
}

router.PathPrefix("/api/videos/random").Methods("GET").HandlerFunc(router.GetRandom).HeadersRegexp("visitor", "[0-9]{10,20}")
router.PathPrefix("/api/videos/{video_id}/{reaction:(?:cool|trash)}").Methods("POST").HandlerFunc(router.WriteReaction).HeadersRegexp("visitor", "[0-9]{10,20}")
router.PathPrefix("/api/videos/{video_id}").Methods("GET").HandlerFunc(router.GetVideo)

router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("frontend/static"))))
router.PathPrefix("/").Methods("GET").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
err := templates.ExecuteTemplate(w, "random.html", nil)
if err != nil {
log.Println(err.Error())
}
})

router.Use(loggingMiddleware)

return router
}

func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.RequestURI)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}

0 comments on commit 99e508d

Please sign in to comment.