aboutsummaryrefslogtreecommitdiff
path: root/api.go
diff options
context:
space:
mode:
authorTim Keller <tjkeller.xyz>2025-05-24 12:52:32 -0500
committerTim Keller <tjkeller.xyz>2025-05-24 12:52:32 -0500
commitbcf66d92d664dd707937ae866830a6bee0751745 (patch)
tree5c1f7ecc037b53b434befe71509cc3009beaf3d7 /api.go
parent6b0385c495b246859d27bfa75e1bd4dfa45c2be2 (diff)
downloadmintube-bcf66d92d664dd707937ae866830a6bee0751745.tar.xz
mintube-bcf66d92d664dd707937ae866830a6bee0751745.zip
cleanup all go code and add an index/home page that is composed from the readme fileHEADmaster
Diffstat (limited to 'api.go')
-rw-r--r--api.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/api.go b/api.go
new file mode 100644
index 0000000..fa91ea6
--- /dev/null
+++ b/api.go
@@ -0,0 +1,58 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+)
+
+const youtubeAPI = "https://www.googleapis.com/youtube/v3/"
+
+/* function to make an api request */
+func apiRequest(w http.ResponseWriter, r *http.Request, endpoint string, videoIdParam string, part string) {
+ videoID := r.URL.Query().Get("id")
+ if videoID == "" {
+ msg := "Missing ?id=VIDEO_ID parameter"
+ http.Error(w, msg, http.StatusBadRequest)
+ return
+ }
+
+ if apiKey == "" {
+ msg := "API_KEY environment variable not set"
+ http.Error(w, msg, http.StatusInternalServerError)
+ log.Println(msg)
+ return
+ }
+
+ url := fmt.Sprintf("%s?part=%s&%s=%s&key=%s", youtubeAPI + endpoint, part, videoIdParam, videoID, apiKey)
+ resp, err := http.Get(url)
+ if err != nil {
+ msg := "Failed to fetch video info: " + err.Error()
+ http.Error(w, msg, http.StatusInternalServerError)
+ log.Println(msg)
+ return
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ msg := "YouTube API error: " + resp.Status
+ http.Error(w, msg, http.StatusBadGateway)
+ log.Println(msg)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ io.Copy(w, resp.Body)
+}
+
+/* routes */
+func setupRoutesAPI() {
+ http.HandleFunc("/api/details", func(w http.ResponseWriter, r *http.Request) {
+ apiRequest(w, r, "videos", "id", "snippet,statistics,topicDetails")
+ })
+
+ http.HandleFunc("/api/comments", func(w http.ResponseWriter, r *http.Request) {
+ apiRequest(w, r, "commentThreads", "videoId", "snippet,replies&maxResults=100")
+ })
+}