|
| 1 | +// Sample Go code for user authorization |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "log" |
| 9 | + "io/ioutil" |
| 10 | + "net/http" |
| 11 | + "net/url" |
| 12 | + "os" |
| 13 | + "os/user" |
| 14 | + "path/filepath" |
| 15 | + |
| 16 | + "golang.org/x/net/context" |
| 17 | + "golang.org/x/oauth2" |
| 18 | + "golang.org/x/oauth2/google" |
| 19 | + "google.golang.org/api/youtube/v3" |
| 20 | +) |
| 21 | + |
| 22 | +const missingClientSecretsMessage = ` |
| 23 | +Please configure OAuth 2.0 |
| 24 | +` |
| 25 | + |
| 26 | +// getClient uses a Context and Config to retrieve a Token |
| 27 | +// then generate a Client. It returns the generated Client. |
| 28 | +func getClient(ctx context.Context, config *oauth2.Config) *http.Client { |
| 29 | + cacheFile, err := tokenCacheFile() |
| 30 | + if err != nil { |
| 31 | + log.Fatalf("Unable to get path to cached credential file. %v", err) |
| 32 | + } |
| 33 | + tok, err := tokenFromFile(cacheFile) |
| 34 | + if err != nil { |
| 35 | + tok = getTokenFromWeb(config) |
| 36 | + saveToken(cacheFile, tok) |
| 37 | + } |
| 38 | + return config.Client(ctx, tok) |
| 39 | +} |
| 40 | + |
| 41 | +// getTokenFromWeb uses Config to request a Token. |
| 42 | +// It returns the retrieved Token. |
| 43 | +func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { |
| 44 | + authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) |
| 45 | + fmt.Printf("Go to the following link in your browser then type the "+ |
| 46 | + "authorization code: \n%v\n", authURL) |
| 47 | + |
| 48 | + var code string |
| 49 | + if _, err := fmt.Scan(&code); err != nil { |
| 50 | + log.Fatalf("Unable to read authorization code %v", err) |
| 51 | + } |
| 52 | + |
| 53 | + tok, err := config.Exchange(oauth2.NoContext, code) |
| 54 | + if err != nil { |
| 55 | + log.Fatalf("Unable to retrieve token from web %v", err) |
| 56 | + } |
| 57 | + return tok |
| 58 | +} |
| 59 | + |
| 60 | +// tokenCacheFile generates credential file path/filename. |
| 61 | +// It returns the generated credential path/filename. |
| 62 | +func tokenCacheFile() (string, error) { |
| 63 | + usr, err := user.Current() |
| 64 | + if err != nil { |
| 65 | + return "", err |
| 66 | + } |
| 67 | + tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials") |
| 68 | + os.MkdirAll(tokenCacheDir, 0700) |
| 69 | + return filepath.Join(tokenCacheDir, |
| 70 | + url.QueryEscape("youtube-go-quickstart.json")), err |
| 71 | +} |
| 72 | + |
| 73 | +// tokenFromFile retrieves a Token from a given file path. |
| 74 | +// It returns the retrieved Token and any read error encountered. |
| 75 | +func tokenFromFile(file string) (*oauth2.Token, error) { |
| 76 | + f, err := os.Open(file) |
| 77 | + if err != nil { |
| 78 | + return nil, err |
| 79 | + } |
| 80 | + t := &oauth2.Token{} |
| 81 | + err = json.NewDecoder(f).Decode(t) |
| 82 | + defer f.Close() |
| 83 | + return t, err |
| 84 | +} |
| 85 | + |
| 86 | +// saveToken uses a file path to create a file and store the |
| 87 | +// token in it. |
| 88 | +func saveToken(file string, token *oauth2.Token) { |
| 89 | + fmt.Printf("Saving credential file to: %s\n", file) |
| 90 | + f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) |
| 91 | + if err != nil { |
| 92 | + log.Fatalf("Unable to cache oauth token: %v", err) |
| 93 | + } |
| 94 | + defer f.Close() |
| 95 | + json.NewEncoder(f).Encode(token) |
| 96 | +} |
| 97 | + |
| 98 | +func handleError(err error, message string) { |
| 99 | + if message == "" { |
| 100 | + message = "Error making API call" |
| 101 | + } |
| 102 | + if err != nil { |
| 103 | + log.Fatalf(message + ": %v", err.Error()) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +func channelsListByUsername(service *youtube.Service, part string, forUsername string) { |
| 108 | + call := service.Channels.List(part) |
| 109 | + call = call.ForUsername(forUsername) |
| 110 | + response, err := call.Do() |
| 111 | + handleError(err, "") |
| 112 | + fmt.Println(fmt.Sprintf("This channel's ID is %s. Its title is '%s', " + |
| 113 | + "and it has %d views.", |
| 114 | + response.Items[0].Id, |
| 115 | + response.Items[0].Snippet.Title, |
| 116 | + response.Items[0].Statistics.ViewCount)) |
| 117 | +} |
| 118 | + |
| 119 | + |
| 120 | +func main() { |
| 121 | + ctx := context.Background() |
| 122 | + |
| 123 | + b, err := ioutil.ReadFile("quickstart_client_secret.json") |
| 124 | + if err != nil { |
| 125 | + log.Fatalf("Unable to read client secret file: %v", err) |
| 126 | + } |
| 127 | + |
| 128 | + // If modifying these scopes, delete your previously saved credentials |
| 129 | + // at ~/.credentials/youtube-go-quickstart.json |
| 130 | + config, err := google.ConfigFromJSON(b, youtube.YoutubeReadonlyScope) |
| 131 | + if err != nil { |
| 132 | + log.Fatalf("Unable to parse client secret file to config: %v", err) |
| 133 | + } |
| 134 | + client := getClient(ctx, config) |
| 135 | + service, err := youtube.New(client) |
| 136 | + |
| 137 | + handleError(err, "Error creating YouTube client") |
| 138 | + |
| 139 | + channelsListByUsername(service, "snippet,contentDetails,statistics", "GoogleDevelopers") |
| 140 | +} |
0 commit comments