Go 版快速入门
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
创建一个向 Directory API 发出请求的 Go 命令行应用。
快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。本快速入门使用一种简化的身份验证方法,该方法适用于测试环境。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据。
本快速入门使用 Google Workspace 推荐的 API 客户端库来处理身份验证和授权流程的一些细节。
目标
前提条件
设置环境
如需完成本快速入门,请设置您的环境。
启用 API
在使用 Google API 之前,您需要在 Google Cloud 项目中将其开启。
您可以在单个 Google Cloud 项目中启用一个或多个 API。
如果您要使用新的 Google Cloud 项目完成本快速入门,请配置 OAuth 同意屏幕。如果您已为 Cloud 项目完成此步骤,请跳至下一部分。
-
在 Google Cloud 控制台中,依次前往菜单 menu
> Google Auth platform
> 品牌推广。
前往“品牌推广”
-
如果您已配置 Google Auth platform,则可以在品牌、受众群体和数据访问中配置以下 OAuth 权限请求页面设置。如果您看到一条消息,指出Google Auth platform 尚未配置,请点击开始:
- 在应用信息下,在应用名称中输入应用的名称。
-
在用户支持电子邮件中,选择一个支持电子邮件地址,以便用户在对自己的同意情况有疑问时与您联系。
-
点击下一步。
-
在受众群体下,选择内部。
-
点击下一步。
-
在联系信息下,输入一个电子邮件地址,以便您接收有关项目变更的通知。
-
点击下一步。
-
在完成部分,查看 Google API 服务用户数据政策,如果您同意该政策,请选择我同意《Google API 服务:用户数据政策》。
-
点击继续。
-
点击创建。
-
目前,您可以跳过添加范围的步骤。
未来,如果您创建的应用供 Google Workspace 组织以外的用户使用,则必须将用户类型更改为外部。然后,添加应用所需的授权范围。如需了解详情,请参阅完整的配置 OAuth 同意指南。
为桌面应用授权凭据
如需对最终用户进行身份验证并访问应用中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,您必须为每个平台分别创建客户端 ID。
-
在 Google Cloud 控制台中,依次前往“菜单”图标 menu
> Google Auth platform
> 客户端。
前往“客户”页面
- 点击创建客户端。
- 依次点击应用类型 > 桌面应用。
- 在名称字段中,输入凭据的名称。此名称仅在 Google Cloud 控制台中显示。
- 点击创建。
新创建的凭据会显示在“OAuth 2.0 客户端 ID”下。
- 将下载的 JSON 文件另存为
credentials.json
,然后将该文件移动到您的工作目录。
准备工作区
创建工作目录:
mkdir quickstart
切换到工作目录:
cd quickstart
初始化新模块:
go mod init quickstart
获取 Directory API Go 客户端库和 OAuth2.0 软件包:
go get google.golang.org/api/admin/directory/v1
go get golang.org/x/oauth2/google
设置示例
在工作目录中,创建一个名为 quickstart.go
的文件。
在文件中,粘贴以下代码:
运行示例
在工作目录中,构建并运行示例:
go run quickstart.go
-
首次运行该示例时,系统会提示您授权访问:
-
如果您尚未登录 Google 账号,请在系统提示时登录。如果您登录了多个账号,请选择一个账号用于授权。
- 点击接受。
您的 Go 应用运行并调用 Directory API。
授权信息存储在文件系统中,因此下次运行示例代码时,系统不会提示您进行授权。
后续步骤
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-28。
[null,null,["最后更新时间 (UTC):2025-08-28。"],[],[],null,["Create a Go command-line application that makes requests to the\nDirectory 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\n- A Google Workspace domain with [API access enabled](https://support.google.com/a/answer/60757).\n- A Google Account in that domain with administrator privileges.\n\n\u003cbr /\u003e\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 Directory API.\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=admin.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 Directory API Go client library and OAuth2.0 package:\n\n ```\n go get google.golang.org/api/admin/directory/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 admin_sdk/directory/quickstart.go \n [View on GitHub](https://github.com/googleworkspace/go-samples/blob/main/admin_sdk/directory/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 \tadmin \"google.golang.org/api/admin/directory/v1\"\n \t\"google.golang.org/api/option\"\n )\n\n // Retrieve a token, saves the token, then returns the generated client.\n func getClient(config *oauth2.Config) *http.Client {\n \t// The file token.json stores the user's access and refresh tokens, and is\n \t// created automatically when the authorization flow completes for the first\n \t// time.\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 // Request 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(context.TODO(), 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 \tif err != nil {\n \t\treturn nil, err\n \t}\n \tdefer f.Close()\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 \tif err != nil {\n \t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n \t}\n \tdefer f.Close()\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, admin.AdminDirectoryUserReadonlyScope)\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 := admin.NewService(ctx, option.WithHTTPClient(client))\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to retrieve directory Client %v\", err)\n \t}\n\n \tr, err := srv.Users.List().Customer(\"my_customer\").MaxResults(10).\n \t\tOrderBy(\"email\").Do()\n \tif err != nil {\n \t\tlog.Fatalf(\"Unable to retrieve users in domain: %v\", err)\n \t}\n\n \tif len(r.Users) == 0 {\n \t\tfmt.Print(\"No users found.\\n\")\n \t} else {\n \t\tfmt.Print(\"Users:\\n\")\n \t\tfor _, u := range r.Users {\n \t\t\tfmt.Printf(\"%s (%s)\\n\", u.PrimaryEmail, u.Name.FullName)\n \t\t}\n \t}\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 Directory 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/admin/directory/v1/guides/troubleshoot-authentication-authorization)\n - [Directory API developer guides](/workspace/admin/directory/v1/guides)\n - [Directory API reference documentation](/workspace/admin/directory/v1/reference)\n - [`google-api-go-client` section of GitHub](https://github.com/google/google-api-go-client)"]]