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

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

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

以下是你提供的代码:

package main

import (
	"context"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	admin "google.golang.org/api/admin/directory/v1"
	"google.golang.org/api/option"
)

func readCsvFile(filePath string) [][]string {
	f, err := os.Open(filePath)
	if err != nil {
		log.Fatal("无法读取输入文件 "+filePath, err)
	}
	defer f.Close()

	csvReader := csv.NewReader(f)
	records, err := csvReader.ReadAll()
	if err != nil {
		log.Fatal("无法解析 CSV 文件 "+filePath, err)
	}

	return records
}

// 获取 token,保存 token,然后返回生成的客户端
func getClient(config *oauth2.Config) *http.Client {
	// token.json 文件存储用户的访问和刷新令牌,在第一次授权流程完成时会自动生成
	tokFile := "token.json"
	tok, err := tokenFromFile(tokFile)
	if err != nil {
		tok = getTokenFromWeb(config)
		saveToken(tokFile, tok)
	}
	return config.Client(context.Background(), tok)
}

// 从网络请求令牌,然后返回获取到的令牌
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
	authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
	fmt.Printf("在浏览器中打开以下链接并输入授权码:\n%v\n", authURL)

	var authCode string
	if _, err := fmt.Scan(&authCode); err != nil {
		log.Fatalf("无法读取授权码:%v", err)
	}

	tok, err := config.Exchange(context.TODO(), authCode)
	if err != nil {
		log.Fatalf("无法从网络中获取令牌:%v", err)
	}
	return tok
}

// 从本地文件中获取令牌
func tokenFromFile(file string) (*oauth2.Token, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	tok := &oauth2.Token{}
	err = json.NewDecoder(f).Decode(tok)
	return tok, err
}

// 将令牌保存到文件路径
func saveToken(path string, token *oauth2.Token) {
	fmt.Printf("将凭证文件保存到:%s\n", path)
	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Fatalf("无法缓存 OAuth 令牌:%v", err)
	}
	defer f.Close()
	json.NewEncoder(f).Encode(token)
}

func findDeviceId(srv *admin.Service, deviceSerial string) (deviceId string) {
	deviceId = ""
	r, err := srv.Chromeosdevices.List("aaa").Query(deviceSerial).Do()
	if err != nil {
		log.Printf("无法在域中检索到序列号为 %s 的设备:%v", deviceSerial, err)
	} else {
		for _, u := range r.Chromeosdevices {
			deviceId = u.DeviceId
			fmt.Printf("%s %s (%s)\n", u.DeviceId, u.SerialNumber, u.Status)
		}
	}
	return deviceId
}

func main() {
	ctx := context.Background()
	b, err := os.ReadFile("credentials.json")
	if err != nil {
		log.Fatalf("无法读取客户端密钥文件:%v", err)
	}

	config, err := google.ConfigFromJSON(b, admin.AdminDirectoryDeviceChromeosScope)
	if err != nil {
		log.Fatalf("无法解析客户端密钥文件为配置:%v", err)
	}
	client := getClient(config)

	srv, err := admin.NewService(ctx, option.WithHTTPClient(client))
	if err != nil {
		log.Fatalf("无法获取目录客户端:%v", err)
	}
	deviceId := findDeviceId(srv, "xxx")

	deviceAction := make(map[string]string)
	deviceAction["action"] = "disable"
	deviceAction["deprovisionReason"] = "retiring_device"

	r, err := srv.Chromeosdevices.Action("aaa", deviceId, &deviceAction).Do()
	fmt.Println(r)
	fmt.Println(err)
}

出现错误:

无法将 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

package main
import (
"context"
"encoding/csv"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
)
func readCsvFile(filePath string) [][]string {
f, err := os.Open(filePath)
if err != nil {
log.Fatal("Unable to read input file "+filePath, err)
}
defer f.Close()
csvReader := csv.NewReader(f)
records, err := csvReader.ReadAll()
if err != nil {
log.Fatal("Unable to parse file as CSV for "+filePath, err)
}
return records
}
// Retrieve a token, saves the token, then returns the generated client.
func getClient(config *oauth2.Config) *http.Client {
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
tokFile := "token.json"
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
// Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(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)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
// Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
// Saves a token to a file path.
func saveToken(path string, 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)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
func findDeviceId(srv *admin.Service, deviceSerial string) (deviceId string) {
deviceId = ""
r, err := srv.Chromeosdevices.List("aaa").Query(deviceSerial).Do()
if err != nil {
log.Printf("Unable to retrieve device with serial %s in domain: %v", deviceSerial, err)
} else {
for _, u := range r.Chromeosdevices {
deviceId = u.DeviceId
fmt.Printf("%s %s (%s)\n", u.DeviceId, u.SerialNumber, u.Status)
}
}
return deviceId
}
func main() {
ctx := context.Background()
b, err := os.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, admin.AdminDirectoryDeviceChromeosScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
srv, err := admin.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve directory Client %v", err)
}
deviceId := findDeviceId(srv, "xxx")
deviceAction := make(map[string]string)
deviceAction["action"] = "disable"
deviceAction["deprovisionReason"] = "retiring_device"
r, err := srv.Chromeosdevices.Action("aaa", deviceId, &deviceAction).Do()
fmt.Println(r)
fmt.Println(err)
}

Getting error

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

答案1

得分: 0

ChromeosdevicesService.Action 方法接受 ChromeOsDeviceAction

chromeosdeviceaction := &admin.ChromeOsDeviceAction{
    Action: "disable",
    DeprovisionReason: "retiring_device",
}

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

英文:

The method ChromeosdevicesService.Action takes ChromeOsDeviceAction:

chromeosdeviceaction := &admin.ChromeOsDeviceAction{
    Action: "disable",
    DeprovisionReason: "retiring_device",
}

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:

确定