登录
首页 >  Golang >  Go问答

使用 Google Apps 脚本调用

来源:stackoverflow

时间:2024-02-15 20:03:22 255浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《使用 Google Apps 脚本调用》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我有以下 google apps 脚本:

function doget(request) {
  var events = calendarapp.getevents(
    new date(number(request.parameters.start) * 1000),
    new date(number(request.parameters.end) * 1000));
  var result = {
    available: events.length == 0
  };
  return contentservice.createtextoutput(json.stringify(result))
    .setmimetype(contentservice.mimetype.json);
}

一旦我在浏览器中打开以下网址:

https://script.google.com/macros/s/akfycbwnggao-p4trbkldgj_blwm5ni9nd5i_0etlns42-puvsrxrm3ovvwfdw/exec?end=1325439000&start=1325437200

我得到了正确的响应:

{"available":true}

我尝试通过 go 进行调用:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
)

func main() {
    site := "https://script.google.com/macros/s/akfycbwnggao-p4trbkldgj_blwm5ni9nd5i_0etlns42-puvsrxrm3ovvwfdw/exec"
    base, err := url.parse(site)
    if err != nil {
        return
    }

    // path params
    //  base.path += "this will get automatically encoded"

    // query params
    params := url.values{}

    params.add("start", "1325437200")
    params.add("end", "1325439000")
    base.rawquery = params.encode()

    fmt.printf("encoded url is %q\n", base.string())

    // make a sample http get request
    res, err := http.get(base.string())
    // check for response error
    if err != nil {
        log.fatal(err)
    }

    // read all response body
    data, _ := ioutil.readall(res.body)

    // close response body
    res.body.close()

    // print `data` as a string
    fmt.printf("%s\n", data)
}

但是我没有得到相同的输出,并且获取很长的文本看起来就像用多种语言提取 google 登录屏幕(无论输出是什么,它都不是预期的),我希望输出为与我在浏览器上得到的相同,即

{"available":true}

解决方案


当我询问您的 Web Apps 中 Execute as:Who has access: 的设置时,我确认在您的设置中,Execute as:Who has access:MeAny one with google accountzqbendcz qb ,分别。

在这种情况下,当您(Web 应用程序的所有者)使用脚本访问您的 Web 应用程序时,需要将访问令牌包含在请求标头中。但是当我看到你的golang脚本时,似乎访问令牌没有用于请求标头。并且,当非 Web Apps 所有者的用户访问 Web Apps 时,需要使用访问令牌,并与用户共享 Web Apps 的 Google Apps 脚本项目。

我担心这些可能是导致您出现问题的原因。

如果您想测试对 Web Apps 的请求,我建议使用 Anyone with Google account: MeWho has access: Anyone 的设置。这样,脚本就可以在不使用访问令牌的情况下运行。而且,不是 Web Apps 所有者的用户也可以访问 Web Apps,而无需使用访问令牌和共享 GAS 项目。

参考:

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Google Apps 脚本调用》文章吧,也可关注golang学习网公众号了解相关技术文章。

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