使用 OAuth 在 Golang 中向 Google API 发送设备状态更新请求的语法
来源:stackoverflow
时间:2024-03-10 10:18:25 303浏览 收藏
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用 OAuth 在 Golang 中向 Google API 发送设备状态更新请求的语法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
我正在尝试更改 chromeos 设备的状态。
我的“获取”请求用于从序列号获取设备 id。
但是,我无法弄清楚 如何在 golang google sdk/api 中传递有效负载 ,因为它是一个“post”请求。
本例中的有效负载是操作。 (取消配置、禁用、重新启用、pre_provisioned_disable、pre_provisioned_reenable)和 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("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)
}
出现错误
cannot use deviceAction (variable of type map[string]string) as *admin.ChromeOsDeviceAction value in argument to srv.Chromeosdevices.ActioncompilerIncompatibleAssign
正确答案
方法 ChromeosdevicesService.Action 需要 ChromeOsDeviceAction:
chromeosdeviceaction := &admin.ChromeOsDeviceAction{
Action: "disable",
DeprovisionReason: "retiring_device",
}
使用应用程序默认凭据,您的代码会更简单、更可移植。库文档中显示并引用了此方法:Creating a client
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 OAuth 在 Golang 中向 Google API 发送设备状态更新请求的语法》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习