-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathyoutube.go
More file actions
52 lines (42 loc) · 1.08 KB
/
youtube.go
File metadata and controls
52 lines (42 loc) · 1.08 KB
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
package main
import (
"errors"
"net/http"
"google.golang.org/api/youtube/v3"
"github.com/google/google-api-go-client/googleapi/transport"
)
// Video is a YouTube video
type Video struct {
ID, Title, File string
}
// Search will find the first video for the search terms
func Search(term string, num int64) (*Video, error) {
client := &http.Client{
Transport: &transport.APIKey{Key: "AIzaSyBzqzgWz6_tucORR3NAGw9XC6qPq0ORanc"},
}
service, err := youtube.New(client)
if err != nil {
return nil, err
}
// Make the API call to YouTube.
call := service.Search.List("id,snippet").
Q(term).
MaxResults(num)
response, err := call.Do()
if err != nil {
return nil, err
}
// Group video, channel, and playlist results in separate lists.
videos := []Video{}
// Iterate through each item and add it to the correct list.
for _, item := range response.Items {
switch item.Id.Kind {
case "youtube#video":
videos = append(videos, Video{item.Id.VideoId, item.Snippet.Title, ""})
}
}
if len(videos) == 0 {
return nil, errors.New("No videos found")
}
return &videos[0], nil
}