Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
utworzyć aplikację wiersza poleceń w Go, która wysyła żądania do interfejsu Google Docs API.
Przewodniki Szybki start wyjaśniają, jak skonfigurować i uruchomić aplikację, która wywołuje interfejs API Google Workspace. W tym krótkim wprowadzeniu użyjemy uproszczonego podejścia do uwierzytelniania, które jest odpowiednie w środowisku testowym. W przypadku środowiska produkcyjnego zalecamy zapoznanie się z informacjami o uwierzytelnianiu i autoryzacji przed wybraniem danych logowania odpowiednich dla Twojej aplikacji.
W tym przewodniku Szybki start używane są zalecane biblioteki klienta interfejsu API Google Workspace, które obsługują niektóre szczegóły procesu uwierzytelniania i autoryzacji.
Aby ukończyć ten przewodnik, skonfiguruj środowisko.
Włącz API
Zanim zaczniesz korzystać z interfejsów Google API, musisz je włączyć w projekcie Google Cloud.
W jednym projekcie Google Cloud możesz włączyć co najmniej 1 interfejs API.
W konsoli Google Cloud włącz interfejs Google Docs API.
Jeśli do wykonania zadań z tego krótkiego wprowadzenia posłużył Ci nowy projekt Google Cloud, skonfiguruj ekran akceptacji OAuth. Jeśli ten krok został już wykonany w przypadku Twojego projektu w Cloud, przejdź do następnej sekcji.
W konsoli Google Cloud otwórz Menu menu>Google Auth platform>Branding.
Jeśli masz już skonfigurowany Google Auth platform, możesz skonfigurować te ustawienia ekranu zgody OAuth w sekcjach Branding, Odbiorcy i Dostęp do danych. Jeśli zobaczysz komunikat Google Auth platform Jeszcze nie skonfigurowano, kliknij Rozpocznij:
W sekcji Informacje o aplikacji w polu Nazwa aplikacji wpisz nazwę aplikacji.
W sekcji Adres e-mail pomocy dla użytkowników wybierz adres e-mail, na który użytkownicy mogą pisać, jeśli mają pytania dotyczące ich zgody.
Kliknij Dalej.
W sekcji Odbiorcy wybierz Wewnętrzny.
Kliknij Dalej.
W sekcji Dane kontaktowe wpisz adres e-mail, na który będziesz otrzymywać powiadomienia o wszelkich zmianach w projekcie.
Na razie możesz pominąć dodawanie zakresów.
W przyszłości, gdy będziesz tworzyć aplikację do użytku poza organizacją Google Workspace, musisz zmienić Typ użytkownika na Zewnętrzny. Następnie dodaj zakresy autoryzacji wymagane przez aplikację. Więcej informacji znajdziesz w pełnym przewodniku Konfigurowanie zgody OAuth.
Autoryzowanie danych logowania w aplikacji na komputer
Aby uwierzytelniać użytkowników i uzyskiwać dostęp do danych użytkowników w aplikacji, musisz utworzyć co najmniej 1 identyfikator klienta OAuth 2.0. Identyfikator klienta wskazuje konkretną aplikację na serwerach OAuth Google. Jeśli Twoja aplikacja działa na kilku platformach, musisz utworzyć osobny identyfikator klienta dla każdej z nich.
W konsoli Google Cloud otwórz Menu menu>Google Auth platform>Klienci.
packagemainimport("context""encoding/json""fmt""log""net/http""os""golang.org/x/oauth2""golang.org/x/oauth2/google""google.golang.org/api/docs/v1""google.golang.org/api/option")// Retrieves a token, saves the token, then returns the generated client.funcgetClient(config*oauth2.Config)*http.Client{tokFile:="token.json"tok,err:=tokenFromFile(tokFile)iferr!=nil{tok=getTokenFromWeb(config)saveToken(tokFile,tok)}returnconfig.Client(context.Background(),tok)}// Requests a token from the web, then 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)varauthCodestringif_,err:=fmt.Scan(&authCode);err!=nil{log.Fatalf("Unable to read authorization code: %v",err)}tok,err:=config.Exchange(oauth2.NoContext,authCode)iferr!=nil{log.Fatalf("Unable to retrieve token from web: %v",err)}returntok}// Retrieves a token from a local file.functokenFromFile(filestring)(*oauth2.Token,error){f,err:=os.Open(file)deferf.Close()iferr!=nil{returnnil,err}tok:=&oauth2.Token{}err=json.NewDecoder(f).Decode(tok)returntok,err}// Saves a token to a file path.funcsaveToken(pathstring,token*oauth2.Token){fmt.Printf("Saving credential file to: %s\n",path)f,err:=os.OpenFile(path,os.O_RDWR|os.O_CREATE|os.O_TRUNC,0600)deferf.Close()iferr!=nil{log.Fatalf("Unable to cache OAuth token: %v",err)}json.NewEncoder(f).Encode(token)}funcmain(){ctx:=context.Background()b,err:=os.ReadFile("credentials.json")iferr!=nil{log.Fatalf("Unable to read client secret file: %v",err)}// If modifying these scopes, delete your previously saved token.json.config,err:=google.ConfigFromJSON(b,"https://www.googleapis.com/auth/documents.readonly")iferr!=nil{log.Fatalf("Unable to parse client secret file to config: %v",err)}client:=getClient(config)srv,err:=docs.NewService(ctx,option.WithHTTPClient(client))iferr!=nil{log.Fatalf("Unable to retrieve Docs client: %v",err)}// Prints the title of the requested doc:// https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/editdocId:="195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"doc,err:=srv.Documents.Get(docId).Do()iferr!=nil{log.Fatalf("Unable to retrieve data from document: %v",err)}fmt.Printf("The title of the doc is: %s\n",doc.Title)}
Uruchamianie przykładu
W katalogu roboczym skompiluj i uruchom przykład:
go run quickstart.go
Przy pierwszym uruchomieniu przykładu pojawi się prośba o autoryzację dostępu:
Jeśli nie zalogowano się na konto Google, pojawi się prośba o zalogowanie. Jeśli logujesz się na wiele kont, wybierz jedno z nich, aby użyć go do autoryzacji.
Kliknij Akceptuję.
Aplikacja Go działa i wywołuje interfejs Google Docs API.
Informacje o autoryzacji są przechowywane w systemie plików, więc przy następnym uruchomieniu przykładowego kodu nie pojawi się prośba o autoryzację.
[[["Łatwo zrozumieć","easyToUnderstand","thumb-up"],["Rozwiązało to mój problem","solvedMyProblem","thumb-up"],["Inne","otherUp","thumb-up"]],[["Brak potrzebnych mi informacji","missingTheInformationINeed","thumb-down"],["Zbyt skomplikowane / zbyt wiele czynności do wykonania","tooComplicatedTooManySteps","thumb-down"],["Nieaktualne treści","outOfDate","thumb-down"],["Problem z tłumaczeniem","translationIssue","thumb-down"],["Problem z przykładami/kodem","samplesCodeIssue","thumb-down"],["Inne","otherDown","thumb-down"]],["Ostatnia aktualizacja: 2025-08-29 UTC."],[],[],null,["Create a Go command-line application that makes requests to the\nGoogle Docs API.\n\nQuickstarts explain how to set up and run an app that calls a\nGoogle Workspace API. This quickstart uses a\nsimplified authentication approach that is appropriate for a testing\nenvironment. For a production environment, we recommend learning about\n[authentication and authorization](/workspace/guides/auth-overview)\nbefore\n[choosing the access credentials](/workspace/guides/create-credentials#choose_the_access_credential_that_is_right_for_you)\nthat are appropriate for your app.\n\nThis quickstart uses Google Workspace's recommended API client libraries\nto handle some details of the authentication and authorization flow.\n\nObjectives\n\n- Set up your environment.\n- Set up the sample.\n- Run the sample.\n\nPrerequisites\n\n- Latest version of [Go](https://golang.org/).\n- Latest version of [Git](https://git-scm.com/).\n- [A Google Cloud project](/workspace/guides/create-project).\n\n\u003c!-- --\u003e\n\n- A Google Account.\n\nSet up your environment\n\nTo complete this quickstart, set up your environment.\n\nEnable the API Before using Google APIs, you need to turn them on in a Google Cloud project. You can turn on one or more APIs in a single Google Cloud project.\n\n- In the Google Cloud console, enable the Google Docs API.\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=docs.googleapis.com)\n\nConfigure the OAuth consent screen\n\nIf you're using a new Google Cloud project to complete this quickstart, configure\nthe OAuth consent screen. If you've already\ncompleted this step for your Cloud project, skip to the next section.\n\n1. In the Google Cloud console, go to Menu menu \\\u003e **Google Auth platform** \\\u003e **Branding** .\n\n [Go to Branding](https://console.cloud.google.com/auth/branding)\n2. If you have already configured the Google Auth platform, you can configure the following OAuth Consent Screen settings in [Branding](https://console.cloud.google.com/auth/branding), [Audience](https://console.cloud.google.com/auth/audience), and [Data Access](https://console.cloud.google.com/auth/scopes). If you see a message that says **Google Auth platform not configured yet** , click **Get Started**:\n 1. Under **App Information** , in **App name**, enter a name for the app.\n 2. In **User support email**, choose a support email address where users can contact you if they have questions about their consent.\n 3. Click **Next**.\n 4. Under **Audience** , select **Internal**.\n 5. Click **Next**.\n 6. Under **Contact Information** , enter an **Email address** where you can be notified about any changes to your project.\n 7. Click **Next**.\n 8. Under **Finish** , review the [Google API Services User Data Policy](https://developers.google.com/terms/api-services-user-data-policy) and if you agree, select **I agree to the Google API Services: User Data Policy**.\n 9. Click **Continue**.\n 10. Click **Create**.\n3. For now, you can skip adding scopes. In the future, when you create an app for use outside of your Google Workspace organization, you must change the **User type** to **External** . Then add the authorization scopes that your app requires. To learn more, see the full [Configure OAuth consent](/workspace/guides/configure-oauth-consent) guide.\n\nAuthorize credentials for a desktop application To authenticate end users and access user data in your app, you need to create one or more OAuth 2.0 Client IDs. A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms, you must create a separate client ID for each platform.\n\n1. In the Google Cloud console, go to Menu menu \\\u003e **Google Auth platform** \\\u003e **Clients** .\n\n [Go to Clients](https://console.cloud.google.com/auth/clients)\n2. Click **Create Client**.\n3. Click **Application type** \\\u003e **Desktop app**.\n4. In the **Name** field, type a name for the credential. This name is only shown in the Google Cloud console.\n5. Click **Create** .\n\n\n The newly created credential appears under \"OAuth 2.0 Client IDs.\"\n6. Save the downloaded JSON file as `credentials.json`, and move the file to your working directory.\n\nPrepare the workspace\n\n1. Create a working directory:\n\n ```\n mkdir quickstart\n ```\n2. Change to the working directory:\n\n ```\n cd quickstart\n ```\n3. Initialize the new module:\n\n ```\n go mod init quickstart\n ```\n4. Get the Google Docs API Go client library and OAuth2.0 package:\n\n ```\n go get google.golang.org/api/docs/v1\n go get golang.org/x/oauth2/google\n ```\n\nSet up the sample\n\n1. In your working directory, create a file named `quickstart.go`.\n\n2. In the file, paste the following code:\n\n\n docs/quickstart/quickstart.go \n [View on GitHub](https://github.com/googleworkspace/go-samples/blob/main/docs/quickstart/quickstart.go) \n\n ```go\n package main\n\n import (\n \t\"context\"\n \t\"encoding/json\"\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n \t\"os\"\n\n \t\"golang.org/x/oauth2\"\n \t\"golang.org/x/oauth2/google\"\n \t\"google.golang.org/api/docs/v1\"\n \t\"google.golang.org/api/option\"\n )\n\n // Retrieves a token, saves the token, then returns the generated client.\n func getClient(config *oauth2.Config) *http.Client {\n \ttokFile := \"token.json\"\n \ttok, err := tokenFromFile(tokFile)\n \tif err != nil {\n \t\ttok = getTokenFromWeb(config)\n \t\tsaveToken(tokFile, tok)\n \t}\n \treturn config.Client(context.Background(), tok)\n }\n\n // Requests a token from the web, then returns the retrieved token.\n func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n \tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n \tfmt.Printf(\"Go to the following link in your browser then type the \"+\n \t\t\"authorization code: \\n%v\\n\", authURL)\n\n \tvar authCode string\n \tif _, err := fmt.Scan(&authCode); err != nil {\n \t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n \t}\n\n \ttok, err := config.Exchange(oauth2.NoContext, authCode)\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n \t}\n \treturn tok\n }\n\n // Retrieves a token from a local file.\n func tokenFromFile(file string) (*oauth2.Token, error) {\n \tf, err := os.Open(file)\n \tdefer f.Close()\n \tif err != nil {\n \t\treturn nil, err\n \t}\n \ttok := &oauth2.Token{}\n \terr = json.NewDecoder(f).Decode(tok)\n \treturn tok, err\n }\n\n // Saves a token to a file path.\n func saveToken(path string, token *oauth2.Token) {\n \tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n \tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n \tdefer f.Close()\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to cache OAuth token: %v\", err)\n \t}\n \tjson.NewEncoder(f).Encode(token)\n }\n\n func main() {\n \tctx := context.Background()\n \tb, err := os.ReadFile(\"credentials.json\")\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to read client secret file: %v\", err)\n \t}\n\n \t// If modifying these scopes, delete your previously saved token.json.\n \tconfig, err := google.ConfigFromJSON(b, \"https://www.googleapis.com/auth/documents.readonly\")\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to parse client secret file to config: %v\", err)\n \t}\n \tclient := getClient(config)\n\n \tsrv, err := docs.NewService(ctx, option.WithHTTPClient(client))\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to retrieve Docs client: %v\", err)\n \t}\n\n \t// Prints the title of the requested doc:\n \t// https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit\n \tdocId := \"195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE\"\n \tdoc, err := srv.Documents.Get(docId).Do()\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to retrieve data from document: %v\", err)\n \t}\n \tfmt.Printf(\"The title of the doc is: %s\\n\", doc.Title)\n }\n ```\n\n \u003cbr /\u003e\n\nRun the sample\n\n1. In your working directory, build and run the sample:\n\n ```\n go run quickstart.go\n ```\n\n\u003c!-- --\u003e\n\n2. The first time you run the sample, it prompts you to authorize access:\n 1. If you're not already signed in to your Google Account, sign in when prompted. If you're signed in to multiple accounts, select one account to use for authorization.\n 2. Click **Accept**.\n\n\n Your Go application runs and calls the Google Docs API.\n\n\n Authorization information is stored in the file system, so the next time you run the sample\n code, you aren't prompted for authorization.\n\nNext steps\n\n- [Try the Google Workspace APIs in the APIs explorer](/workspace/explore)\n - [Troubleshoot authentication and authorization issues](/workspace/docs/api/troubleshoot-authentication-authorization)\n - [Docs API reference documentation](/workspace/docs/api/reference/rest)\n - [`google-api-go-client` section of GitHub](https://github.com/google/google-api-go-client)"]]