-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Dima
committed
Nov 4, 2023
1 parent
44697ff
commit 99e508d
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} |