Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Hoàn tất các bước được mô tả trong phần còn lại của trang này và trong khoảng 5 phút, bạn sẽ có một ứng dụng dòng lệnh Go đơn giản để đưa ra các yêu cầu cho YouTube Data API.
Mã mẫu được dùng trong hướng dẫn này sẽ truy xuất tài nguyên channel cho kênh GoogleDevelopers trên YouTube và in một số thông tin cơ bản từ tài nguyên đó.
Có quyền truy cập vào Internet và trình duyệt web.
Tài khoản Google.
Bước 1: Bật YouTube Data API
Sử dụng trình hướng dẫn này để tạo hoặc chọn một dự án trong Google Developers Console và tự động bật API. Nhấp vào Tiếp tục, rồi nhấp vào Chuyển đến phần thông tin đăng nhập.
Trên trang Tạo thông tin xác thực, hãy nhấp vào nút Huỷ.
Ở đầu trang, hãy chọn thẻ Màn hình xin phép bằng OAuth.
Chọn một Địa chỉ email, nhập Tên sản phẩm nếu chưa đặt và nhấp vào nút Lưu.
Chọn thẻ Thông tin xác thực, nhấp vào nút Tạo thông tin xác thực rồi chọn Mã ứng dụng OAuth.
Chọn loại ứng dụng Khác, nhập tên "YouTube Data API Quickstart" rồi nhấp vào nút Tạo.
Nhấp vào OK để đóng hộp thoại kết quả.
Nhấp vào nút file_download (Tải JSON xuống) ở bên phải mã nhận dạng ứng dụng.
Di chuyển tệp đã tải xuống vào thư mục đang hoạt động rồi đổi tên thành client_secret.json.
Bước 2: Chuẩn bị không gian làm việc
Đặt biến môi trường GOPATH thành thư mục đang hoạt động của bạn.
Tải thư viện ứng dụng Go của YouTube Data API và gói OAuth2 bằng các lệnh sau:
go get -u google.golang.org/api/youtube/v3go get -u golang.org/x/oauth2/...
Bước 3: Thiết lập mẫu
Tạo một tệp có tên là quickstart.go trong thư mục làm việc của bạn rồi sao chép mã sau:
// Sample Go code for user authorizationpackagemainimport("encoding/json""fmt""log""io/ioutil""net/http""net/url""os""os/user""path/filepath""golang.org/x/net/context""golang.org/x/oauth2""golang.org/x/oauth2/google""google.golang.org/api/youtube/v3")constmissingClientSecretsMessage=`Please configure OAuth 2.0`// getClient uses a Context and Config to retrieve a Token// then generate a Client. It returns the generated Client.funcgetClient(ctxcontext.Context,config*oauth2.Config)*http.Client{cacheFile,err:=tokenCacheFile()iferr!=nil{log.Fatalf("Unable to get path to cached credential file. %v",err)}tok,err:=tokenFromFile(cacheFile)iferr!=nil{tok=getTokenFromWeb(config)saveToken(cacheFile,tok)}returnconfig.Client(ctx,tok)}// getTokenFromWeb uses Config to request a Token.// It returns the retrieved Token.funcgetTokenFromWeb(config*oauth2.Config)*oauth2.Token{authURL:=config.AuthCodeURL("state-token",oauth2.AccessTypeOffline)fmt.Printf("Go to the following link in your browser then type the "+"authorization code: \n%v\n",authURL)varcodestringif_,err:=fmt.Scan(&code);err!=nil{log.Fatalf("Unable to read authorization code %v",err)}tok,err:=config.Exchange(oauth2.NoContext,code)iferr!=nil{log.Fatalf("Unable to retrieve token from web %v",err)}returntok}// tokenCacheFile generates credential file path/filename.// It returns the generated credential path/filename.functokenCacheFile()(string,error){usr,err:=user.Current()iferr!=nil{return"",err}tokenCacheDir:=filepath.Join(usr.HomeDir,".credentials")os.MkdirAll(tokenCacheDir,0700)returnfilepath.Join(tokenCacheDir,url.QueryEscape("youtube-go-quickstart.json")),err}// tokenFromFile retrieves a Token from a given file path.// It returns the retrieved Token and any read error encountered.functokenFromFile(filestring)(*oauth2.Token,error){f,err:=os.Open(file)iferr!=nil{returnnil,err}t:=&oauth2.Token{}err=json.NewDecoder(f).Decode(t)deferf.Close()returnt,err}// saveToken uses a file path to create a file and store the// token in it.funcsaveToken(filestring,token*oauth2.Token){fmt.Printf("Saving credential file to: %s\n",file)f,err:=os.OpenFile(file,os.O_RDWR|os.O_CREATE|os.O_TRUNC,0600)iferr!=nil{log.Fatalf("Unable to cache oauth token: %v",err)}deferf.Close()json.NewEncoder(f).Encode(token)}funchandleError(errerror,messagestring){ifmessage==""{message="Error making API call"}iferr!=nil{log.Fatalf(message+": %v",err.Error())}}funcchannelsListByUsername(service*youtube.Service,partstring,forUsernamestring){call:=service.Channels.List(part)call=call.ForUsername(forUsername)response,err:=call.Do()handleError(err,"")fmt.Println(fmt.Sprintf("This channel's ID is %s. Its title is '%s', "+"and it has %d views.",response.Items[0].Id,response.Items[0].Snippet.Title,response.Items[0].Statistics.ViewCount))}funcmain(){ctx:=context.Background()b,err:=ioutil.ReadFile("client_secret.json")iferr!=nil{log.Fatalf("Unable to read client secret file: %v",err)}// If modifying these scopes, delete your previously saved credentials// at ~/.credentials/youtube-go-quickstart.jsonconfig,err:=google.ConfigFromJSON(b,youtube.YoutubeReadonlyScope)iferr!=nil{log.Fatalf("Unable to parse client secret file to config: %v",err)}client:=getClient(ctx,config)service,err:=youtube.New(client)handleError(err,"Error creating YouTube client")channelsListByUsername(service,"snippet,contentDetails,statistics","GoogleDevelopers")}
Tạo và chạy mẫu bằng lệnh sau đây trong thư mục làm việc:
go run quickstart.go
Trong lần đầu tiên bạn chạy mẫu, mẫu này sẽ nhắc bạn uỷ quyền truy cập:
Duyệt đến URL được cung cấp trong trình duyệt web.
Nếu chưa đăng nhập vào Tài khoản Google, bạn sẽ được nhắc đăng nhập. Nếu đã đăng nhập vào nhiều Tài khoản Google, bạn sẽ được yêu cầu chọn một tài khoản để dùng cho việc uỷ quyền.
Nhấp vào nút Chấp nhận.
Sao chép mã bạn nhận được, dán mã đó vào dấu nhắc dòng lệnh rồi nhấn phím Enter.
Ghi chú
Thông tin uỷ quyền được lưu trữ trên hệ thống tệp, vì vậy, các lần thực thi tiếp theo sẽ không nhắc bạn uỷ quyền.
Quy trình uỷ quyền trong ví dụ này được thiết kế cho một ứng dụng dòng lệnh. Để biết thông tin về cách thực hiện uỷ quyền trong một ứng dụng web, hãy xem bài viết Sử dụng OAuth 2.0 cho ứng dụng máy chủ web.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-21 UTC."],[[["\u003cp\u003eThis guide walks you through creating a simple Go command-line application that interacts with the YouTube Data API within about five minutes.\u003c/p\u003e\n"],["\u003cp\u003eThe application retrieves the \u003ccode\u003echannel\u003c/code\u003e resource for the GoogleDevelopers YouTube channel and outputs its ID, title, and view count.\u003c/p\u003e\n"],["\u003cp\u003ePrerequisites include the latest versions of Go and Git, a web browser, internet access, and a Google account.\u003c/p\u003e\n"],["\u003cp\u003eThe guide covers turning on the YouTube Data API, preparing the workspace by setting the \u003ccode\u003eGOPATH\u003c/code\u003e variable and getting necessary packages, and setting up the sample Go code.\u003c/p\u003e\n"],["\u003cp\u003eRunning the sample involves a one-time authorization process through a web browser, after which authorization information is stored for subsequent executions.\u003c/p\u003e\n"]]],["First, enable the YouTube Data API in the Google Developers Console and create OAuth credentials, downloading `client_secret.json`. Next, set the `GOPATH` environment variable and use `go get` to acquire the YouTube Data API Go client library and OAuth2 package. Create `quickstart.go` with the provided code. Then run the sample with `go run quickstart.go`. This prompts you to authorize access via a web browser. Finally, copy and paste the provided code into the command line to complete the authorization.\n"],null,["# Go Quickstart\n\nComplete the steps described in the rest of this page, and in about five minutes\nyou'll have a simple Go command-line application that makes requests to the\nYouTube Data API.\nThe sample code used in this guide retrieves the `channel` resource for the GoogleDevelopers YouTube channel and prints some basic information from that resource.\n\nPrerequisites\n-------------\n\nTo run this quickstart, you'll need:\n\n- [Go](https://golang.org/), latest version recommended.\n- [Git](https://git-scm.com/), latest version recommended.\n- Access to the internet and a web browser.\n- A Google account.\n\nStep 1: Turn on the YouTube Data API\n------------------------------------\n\n1. Use\n [this wizard](https://console.developers.google.com/start/api?id=youtube)\n to create or select a project in the Google Developers Console and\n automatically turn on the API. Click **Continue** , then\n **Go to credentials**.\n\n2. On the **Create credentials** page, click the\n **Cancel** button.\n\n3. At the top of the page, select the **OAuth consent screen** tab.\n Select an **Email address** , enter a **Product name** if not\n already set, and click the **Save** button.\n\n4. Select the **Credentials** tab, click the **Create credentials**\n button and select **OAuth client ID**.\n\n5. Select the application type **Other** , enter the name\n \"YouTube Data API Quickstart\", and click the **Create** button.\n\n6. Click **OK** to dismiss the resulting dialog.\n\n7. Click the file_download\n (Download JSON) button to the right of the client ID.\n\n8. Move the downloaded file to your working directory and rename it\n `client_secret.json`.\n\nStep 2: Prepare the workspace\n-----------------------------\n\n1. Set the `GOPATH` environment variable to your working directory.\n2. Get the YouTube Data API Go client library and OAuth2 package using the following commands:\n\n go get -u google.golang.org/api/youtube/v3\n go get -u golang.org/x/oauth2/...\n\nStep 3: Set up the sample\n-------------------------\n\nCreate a file named `quickstart.go` in your working directory and copy\nin the following code:\n\n\n```go\n// Sample Go code for user authorization\n\npackage main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"log\"\n \"io/ioutil\"\n \"net/http\"\n \"net/url\"\n \"os\"\n \"os/user\"\n \"path/filepath\"\n\n \"golang.org/x/net/context\"\n \"golang.org/x/oauth2\"\n \"golang.org/x/oauth2/google\"\n \"google.golang.org/api/youtube/v3\"\n)\n\nconst missingClientSecretsMessage = `\nPlease configure OAuth 2.0\n`\n\n// getClient uses a Context and Config to retrieve a Token\n// then generate a Client. It returns the generated Client.\nfunc getClient(ctx context.Context, config *oauth2.Config) *http.Client {\n cacheFile, err := tokenCacheFile()\n if err != nil {\n log.Fatalf(\"Unable to get path to cached credential file. %v\", err)\n }\n tok, err := tokenFromFile(cacheFile)\n if err != nil {\n tok = getTokenFromWeb(config)\n saveToken(cacheFile, tok)\n }\n return config.Client(ctx, tok)\n}\n\n// getTokenFromWeb uses Config to request a Token.\n// It returns the retrieved Token.\nfunc getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var code string\n if _, err := fmt.Scan(&code); err != nil {\n log.Fatalf(\"Unable to read authorization code %v\", err)\n }\n\n tok, err := config.Exchange(oauth2.NoContext, code)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web %v\", err)\n }\n return tok\n}\n\n// tokenCacheFile generates credential file path/filename.\n// It returns the generated credential path/filename.\nfunc tokenCacheFile() (string, error) {\n usr, err := user.Current()\n if err != nil {\n return \"\", err\n }\n tokenCacheDir := filepath.Join(usr.HomeDir, \".credentials\")\n os.MkdirAll(tokenCacheDir, 0700)\n return filepath.Join(tokenCacheDir,\n url.QueryEscape(\"youtube-go-quickstart.json\")), err\n}\n\n// tokenFromFile retrieves a Token from a given file path.\n// It returns the retrieved Token and any read error encountered.\nfunc tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n t := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(t)\n defer f.Close()\n return t, err\n}\n\n// saveToken uses a file path to create a file and store the\n// token in it.\nfunc saveToken(file string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", file)\n f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}\n\nfunc handleError(err error, message string) {\n if message == \"\" {\n message = \"Error making API call\"\n }\n if err != nil {\n log.Fatalf(message + \": %v\", err.Error())\n }\n}\n\nfunc channelsListByUsername(service *youtube.Service, part string, forUsername string) {\n call := service.Channels.List(part)\n call = call.ForUsername(forUsername)\n response, err := call.Do()\n handleError(err, \"\")\n fmt.Println(fmt.Sprintf(\"This channel's ID is %s. Its title is '%s', \" +\n \"and it has %d views.\",\n response.Items[0].Id,\n response.Items[0].Snippet.Title,\n response.Items[0].Statistics.ViewCount))\n}\n\n\nfunc main() {\n ctx := context.Background()\n\n b, err := ioutil.ReadFile(\"client_secret.json\")\n if err != nil {\n log.Fatalf(\"Unable to read client secret file: %v\", err)\n }\n\n // If modifying these scopes, delete your previously saved credentials\n // at ~/.credentials/youtube-go-quickstart.json\n config, err := google.ConfigFromJSON(b, youtube.YoutubeReadonlyScope)\n if err != nil {\n log.Fatalf(\"Unable to parse client secret file to config: %v\", err)\n }\n client := getClient(ctx, config)\n service, err := youtube.New(client)\n\n handleError(err, \"Error creating YouTube client\")\n\n channelsListByUsername(service, \"snippet,contentDetails,statistics\", \"GoogleDevelopers\")\n}\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/go/quickstart.go\n```\n\n\u003cbr /\u003e\n\nStep 4: Run the sample\n----------------------\n\nBuild and run the sample using the following command from your working\ndirectory: \n\n go run quickstart.go\n\nThe first time you run the sample, it will prompt you to authorize access:\n\n1. Browse to the provided URL in your web browser.\n\n If you are not already logged into your Google account, you will be\n prompted to log in. If you are logged into multiple Google accounts, you\n will be asked to select one account to use for the authorization.\n2. Click the **Accept** button.\n3. Copy the code you're given, paste it into the command-line prompt, and press **Enter**.\n\nIt worked! **Great!** Check out the further reading section below to learn more.\nI got an error **Bummer.** Thanks for letting us know and we'll work to fix this quickstart.\n\nNotes\n-----\n\n- Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.\n- The authorization flow in this example is designed for a command-line application. For information on how to perform authorization in a web application, see [Using OAuth 2.0 for Web Server Applications](/youtube/v3/guides/auth/server-side-web-apps).\n\nFurther reading\n---------------\n\n- [Google Developers Console help documentation](/console/help/new)\n- [Google APIs Client for Go](https://github.com/google/google-api-go-client)\n- [YouTube Data API reference documentation](/youtube/v3/docs)"]]