package main import ( "context" "encoding/json" "fmt" "net/http" "github.com/julienschmidt/httprouter" "google.golang.org/api/option" "google.golang.org/api/youtube/v3" ) type YoutubeStats struct { Subscribers int `json:"subscribers"` ChannelName string `json:"channelName"` Views int `json:"views"` } func getChannelStats(apiKey string, channelID string) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { ctx := context.Background() yts, err := youtube.NewService(ctx, option.WithAPIKey(apiKey)) if err != nil { fmt.Printf("Error creating new YouTube service: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } call := yts.Channels.List([]string{"snippet,contentDetails,statistics"}) response, err := call.Id(channelID).Do() if err != nil { fmt.Printf("Error calling YouTube API: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } if len(response.Items) > 0 { yt := YoutubeStats{ Subscribers: int(response.Items[0].Statistics.SubscriberCount), ChannelName: response.Items[0].Snippet.Title, Views: int(response.Items[0].Statistics.ViewCount), } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(yt); err != nil { w.WriteHeader(http.StatusBadRequest) return } } else { w.WriteHeader(http.StatusBadRequest) return } } }