52 lines
1.1 KiB
Go
52 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
)
|
|
|
|
type videoMeta struct {
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
}
|
|
|
|
type ytVideosResponse struct {
|
|
Items []struct {
|
|
Snippet struct {
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
} `json:"snippet"`
|
|
} `json:"items"`
|
|
}
|
|
|
|
func fetchVideoMeta(videoID, apiKey string) (*videoMeta, error) {
|
|
q := url.Values{}
|
|
q.Set("part", "snippet")
|
|
q.Set("id", videoID)
|
|
q.Set("key", apiKey)
|
|
|
|
resp, err := http.Get("https://www.googleapis.com/youtube/v3/videos?" + q.Encode())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("youtube api status %d", resp.StatusCode)
|
|
}
|
|
|
|
var parsed ytVideosResponse
|
|
if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(parsed.Items) == 0 {
|
|
return nil, fmt.Errorf("video not found: %s", videoID)
|
|
}
|
|
|
|
return &videoMeta{
|
|
Title: parsed.Items[0].Snippet.Title,
|
|
Description: parsed.Items[0].Snippet.Description,
|
|
}, nil
|
|
}
|