-
Notifications
You must be signed in to change notification settings - Fork 1
/
search_by_keyword.go
72 lines (60 loc) · 1.85 KB
/
search_by_keyword.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"flag"
"fmt"
"log"
"net/http"
"google.golang.org/api/googleapi/transport"
"google.golang.org/api/youtube/v3"
)
var (
query = flag.String("query", "Marble Track 3 construction", "Search term")
maxResults = flag.Int64("max-results", 25, "Max YouTube results")
)
// create key at https://console.developers.google.com/apis/credentials
const developerKey = "YOUR DEVELOPER KEY"
func main() {
flag.Parse()
client := &http.Client{
Transport: &transport.APIKey{Key: developerKey},
}
service, err := youtube.New(client)
if err != nil {
log.Fatalf("Error creating new YouTube client: %v", err)
}
// Make the API call to YouTube.
call := service.Search.List("id,snippet").
Q(*query).
MaxResults(*maxResults)
response, err := call.Do()
handleError(err, "")
// Group video, channel, and playlist results in separate lists.
videos := make(map[string]string)
channels := make(map[string]string)
playlists := make(map[string]string)
// Iterate through each item and add it to the correct list.
for _, item := range response.Items {
switch item.Id.Kind {
case "youtube#video":
videos[item.Id.VideoId] = item.Snippet.Title
case "youtube#channel":
channels[item.Id.ChannelId] = item.Snippet.Title
case "youtube#playlist":
playlists[item.Id.PlaylistId] = item.Snippet.Title
}
}
printIDs("Videos", videos)
printIDs("Channels", channels)
printIDs("Playlists", playlists)
}
// Print the ID and title of each result in a list as well as a name that
// identifies the list. For example, print the word section name "Videos"
// above a list of video search results, followed by the video ID and title
// of each matching video.
func printIDs(sectionName string, matches map[string]string) {
fmt.Printf("%v:\n", sectionName)
for id, title := range matches {
fmt.Printf("[%v] %v\n", id, title)
}
fmt.Printf("\n\n")
}