登录
首页 >  Golang >  Go问答

使用 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学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>