代码之家  ›  专栏  ›  技术社区  ›  Hasan A Yousef Michael Benjamin

从Golang调用Google Apps脚本

  •  0
  • Hasan A Yousef Michael Benjamin  · 技术社区  · 3 年前

    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);
    }
    

    一旦我在browsr打开以下url:

    https://script.google.com/macros/s/AKfycbwNGgAO-p4TrbKLdGj_blwm5nI9nD5i_0EtlnS42-PuVsrxrM3Ovvwfdw/exec?end=1325439000&start=1325437200
    

    我得到了正确的回答:

    {"available":true}
    

    我正试着通过以下方式打电话:

    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)
    }
    

    {“可用”:true}
    
    0 回复  |  直到 3 年前
        1
  •  2
  •   Tanaike    3 年前

    当我问起 Execute as: Who has access: 执行方式: 谁有权访问: Me Any one with google account 分别是。

    我担心这些可能是你问题的原因。

    如果要测试对Web应用程序的请求,建议使用的设置 Anyone with Google account: Me Who has access: Anyone . 这样,脚本就可以在不使用访问令牌的情况下工作。而且,不是Web应用所有者的用户可以访问Web应用,而无需使用访问令牌和共享GAS项目。

    参考文献: