Golang和Google API – 在使用OAuth进行设备状态更新时的POST请求语法

huangapple go评论112阅读模式
英文:

Golang and google api - post request syntax while using oauth for devices status update

问题

我正在尝试更改 ChromeOS 设备的状态。

我的 "get" 请求可以通过序列号获取设备 ID。

然而,我无法弄清楚如何在 Golang 的 Google SDK/API 中传递有效载荷,因为这是一个 "post" 请求。

在这种情况下,有效载荷是操作(deprovision、disable、reenable、pre_provisioned_disable、pre_provisioned_reenable),如果操作是 deprovision,则还有 deprovisionReason。

https://developers.google.com/admin-sdk/directory/reference/rest/v1/chromeosdevices/action#ChromeOsDeviceAction

以下是你提供的代码:

  1. package main
  2. import (
  3. "context"
  4. "encoding/csv"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "golang.org/x/oauth2"
  11. "golang.org/x/oauth2/google"
  12. admin "google.golang.org/api/admin/directory/v1"
  13. "google.golang.org/api/option"
  14. )
  15. func readCsvFile(filePath string) [][]string {
  16. f, err := os.Open(filePath)
  17. if err != nil {
  18. log.Fatal("无法读取输入文件 "+filePath, err)
  19. }
  20. defer f.Close()
  21. csvReader := csv.NewReader(f)
  22. records, err := csvReader.ReadAll()
  23. if err != nil {
  24. log.Fatal("无法解析 CSV 文件 "+filePath, err)
  25. }
  26. return records
  27. }
  28. // 获取 token,保存 token,然后返回生成的客户端
  29. func getClient(config *oauth2.Config) *http.Client {
  30. // token.json 文件存储用户的访问和刷新令牌,在第一次授权流程完成时会自动生成
  31. tokFile := "token.json"
  32. tok, err := tokenFromFile(tokFile)
  33. if err != nil {
  34. tok = getTokenFromWeb(config)
  35. saveToken(tokFile, tok)
  36. }
  37. return config.Client(context.Background(), tok)
  38. }
  39. // 从网络请求令牌,然后返回获取到的令牌
  40. func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
  41. authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
  42. fmt.Printf("在浏览器中打开以下链接并输入授权码:\n%v\n", authURL)
  43. var authCode string
  44. if _, err := fmt.Scan(&authCode); err != nil {
  45. log.Fatalf("无法读取授权码:%v", err)
  46. }
  47. tok, err := config.Exchange(context.TODO(), authCode)
  48. if err != nil {
  49. log.Fatalf("无法从网络中获取令牌:%v", err)
  50. }
  51. return tok
  52. }
  53. // 从本地文件中获取令牌
  54. func tokenFromFile(file string) (*oauth2.Token, error) {
  55. f, err := os.Open(file)
  56. if err != nil {
  57. return nil, err
  58. }
  59. defer f.Close()
  60. tok := &oauth2.Token{}
  61. err = json.NewDecoder(f).Decode(tok)
  62. return tok, err
  63. }
  64. // 将令牌保存到文件路径
  65. func saveToken(path string, token *oauth2.Token) {
  66. fmt.Printf("将凭证文件保存到:%s\n", path)
  67. f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  68. if err != nil {
  69. log.Fatalf("无法缓存 OAuth 令牌:%v", err)
  70. }
  71. defer f.Close()
  72. json.NewEncoder(f).Encode(token)
  73. }
  74. func findDeviceId(srv *admin.Service, deviceSerial string) (deviceId string) {
  75. deviceId = ""
  76. r, err := srv.Chromeosdevices.List("aaa").Query(deviceSerial).Do()
  77. if err != nil {
  78. log.Printf("无法在域中检索到序列号为 %s 的设备:%v", deviceSerial, err)
  79. } else {
  80. for _, u := range r.Chromeosdevices {
  81. deviceId = u.DeviceId
  82. fmt.Printf("%s %s (%s)\n", u.DeviceId, u.SerialNumber, u.Status)
  83. }
  84. }
  85. return deviceId
  86. }
  87. func main() {
  88. ctx := context.Background()
  89. b, err := os.ReadFile("credentials.json")
  90. if err != nil {
  91. log.Fatalf("无法读取客户端密钥文件:%v", err)
  92. }
  93. config, err := google.ConfigFromJSON(b, admin.AdminDirectoryDeviceChromeosScope)
  94. if err != nil {
  95. log.Fatalf("无法解析客户端密钥文件为配置:%v", err)
  96. }
  97. client := getClient(config)
  98. srv, err := admin.NewService(ctx, option.WithHTTPClient(client))
  99. if err != nil {
  100. log.Fatalf("无法获取目录客户端:%v", err)
  101. }
  102. deviceId := findDeviceId(srv, "xxx")
  103. deviceAction := make(map[string]string)
  104. deviceAction["action"] = "disable"
  105. deviceAction["deprovisionReason"] = "retiring_device"
  106. r, err := srv.Chromeosdevices.Action("aaa", deviceId, &deviceAction).Do()
  107. fmt.Println(r)
  108. fmt.Println(err)
  109. }

出现错误:

  1. 无法将 deviceAction(类型为 map[string]string 的变量)作为 *admin.ChromeOsDeviceAction 类型的参数传递给 srv.Chromeosdevices.Action

希望这些信息对你有所帮助!如果你有任何其他问题,请随时问我。

英文:

I am trying to change the status of the chromeos device.

My "get" request works with getting the device ID from the serial number.

However, I am not able to figure out how to pass the payload in golang google sdk/api, since it is a "post" request.

The payload in this case is the Action. (deprovision, disable, reenable, pre_provisioned_disable, pre_provisioned_reenable) and deprovisionReason if action is deprovision.

https://developers.google.com/admin-sdk/directory/reference/rest/v1/chromeosdevices/action#ChromeOsDeviceAction

  1. package main
  2. import (
  3. "context"
  4. "encoding/csv"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "golang.org/x/oauth2"
  11. "golang.org/x/oauth2/google"
  12. admin "google.golang.org/api/admin/directory/v1"
  13. "google.golang.org/api/option"
  14. )
  15. func readCsvFile(filePath string) [][]string {
  16. f, err := os.Open(filePath)
  17. if err != nil {
  18. log.Fatal("Unable to read input file "+filePath, err)
  19. }
  20. defer f.Close()
  21. csvReader := csv.NewReader(f)
  22. records, err := csvReader.ReadAll()
  23. if err != nil {
  24. log.Fatal("Unable to parse file as CSV for "+filePath, err)
  25. }
  26. return records
  27. }
  28. // Retrieve a token, saves the token, then returns the generated client.
  29. func getClient(config *oauth2.Config) *http.Client {
  30. // The file token.json stores the user's access and refresh tokens, and is
  31. // created automatically when the authorization flow completes for the first
  32. // time.
  33. tokFile := "token.json"
  34. tok, err := tokenFromFile(tokFile)
  35. if err != nil {
  36. tok = getTokenFromWeb(config)
  37. saveToken(tokFile, tok)
  38. }
  39. return config.Client(context.Background(), tok)
  40. }
  41. // Request a token from the web, then returns the retrieved token.
  42. func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
  43. authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
  44. fmt.Printf("Go to the following link in your browser then type the "+
  45. "authorization code: \n%v\n", authURL)
  46. var authCode string
  47. if _, err := fmt.Scan(&authCode); err != nil {
  48. log.Fatalf("Unable to read authorization code: %v", err)
  49. }
  50. tok, err := config.Exchange(context.TODO(), authCode)
  51. if err != nil {
  52. log.Fatalf("Unable to retrieve token from web: %v", err)
  53. }
  54. return tok
  55. }
  56. // Retrieves a token from a local file.
  57. func tokenFromFile(file string) (*oauth2.Token, error) {
  58. f, err := os.Open(file)
  59. if err != nil {
  60. return nil, err
  61. }
  62. defer f.Close()
  63. tok := &oauth2.Token{}
  64. err = json.NewDecoder(f).Decode(tok)
  65. return tok, err
  66. }
  67. // Saves a token to a file path.
  68. func saveToken(path string, token *oauth2.Token) {
  69. fmt.Printf("Saving credential file to: %s\n", path)
  70. f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  71. if err != nil {
  72. log.Fatalf("Unable to cache oauth token: %v", err)
  73. }
  74. defer f.Close()
  75. json.NewEncoder(f).Encode(token)
  76. }
  77. func findDeviceId(srv *admin.Service, deviceSerial string) (deviceId string) {
  78. deviceId = ""
  79. r, err := srv.Chromeosdevices.List("aaa").Query(deviceSerial).Do()
  80. if err != nil {
  81. log.Printf("Unable to retrieve device with serial %s in domain: %v", deviceSerial, err)
  82. } else {
  83. for _, u := range r.Chromeosdevices {
  84. deviceId = u.DeviceId
  85. fmt.Printf("%s %s (%s)\n", u.DeviceId, u.SerialNumber, u.Status)
  86. }
  87. }
  88. return deviceId
  89. }
  90. func main() {
  91. ctx := context.Background()
  92. b, err := os.ReadFile("credentials.json")
  93. if err != nil {
  94. log.Fatalf("Unable to read client secret file: %v", err)
  95. }
  96. config, err := google.ConfigFromJSON(b, admin.AdminDirectoryDeviceChromeosScope)
  97. if err != nil {
  98. log.Fatalf("Unable to parse client secret file to config: %v", err)
  99. }
  100. client := getClient(config)
  101. srv, err := admin.NewService(ctx, option.WithHTTPClient(client))
  102. if err != nil {
  103. log.Fatalf("Unable to retrieve directory Client %v", err)
  104. }
  105. deviceId := findDeviceId(srv, "xxx")
  106. deviceAction := make(map[string]string)
  107. deviceAction["action"] = "disable"
  108. deviceAction["deprovisionReason"] = "retiring_device"
  109. r, err := srv.Chromeosdevices.Action("aaa", deviceId, &deviceAction).Do()
  110. fmt.Println(r)
  111. fmt.Println(err)
  112. }

Getting error

  1. cannot use deviceAction (variable of type map[string]string) as *admin.ChromeOsDeviceAction value in argument to srv.Chromeosdevices.ActioncompilerIncompatibleAssign

答案1

得分: 0

ChromeosdevicesService.Action 方法接受 ChromeOsDeviceAction

  1. chromeosdeviceaction := &admin.ChromeOsDeviceAction{
  2. Action: "disable",
  3. DeprovisionReason: "retiring_device",
  4. }

使用应用程序默认凭据,你的代码会更简单和更易移植。这种方法在库的文档中有展示和引用:创建客户端

英文:

The method ChromeosdevicesService.Action takes ChromeOsDeviceAction:

  1. chromeosdeviceaction := &admin.ChromeOsDeviceAction{
  2. Action: "disable",
  3. DeprovisionReason: "retiring_device",
  4. }

Your code would be simpler and more portable using Application Default Credentials. This approach is shown and referenced in the library's documentation: Creating a client

huangapple
  • 本文由 发表于 2022年11月16日 08:24:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/74453727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定