doulu6929 2019-05-23 16:31
浏览 2
已采纳

我应该为日历API重用服务,还是可以安全地按需创建新服务?

I've made a small web server that creates and updates calendar events. However, I'm a bit uncertain about how I'm supposed to use the calendar api library service. At the moment I'm creating a new one each time the web server accepts a request, like so:

ctx := context.Background()
srv, err := calendar.NewService(ctx,option.WithTokenSource(config.TokenSource(ctx)))

I suspect I'm probably supposed to reuse this service, but I can't find any documentation about this. Is it safe to reuse? Does it get discarded automatically when no longer in use (i.e. garbage collection)?

  • 写回答

1条回答 默认 最新

  • dowjgrm6787 2019-05-26 10:09
    关注

    You probably want to use req.Context() (where req is your *http.Request) instead of context.Background(). In this case, you have to create a new service object each time, and they will be garbage collected as appropriate.

    The only reason you would want to use context.Background() is if you're asynchronously issuing the calendar API requests (eg, in a separate goroutine) and they might not finish before the HTTP request finishes. In this case, you could use a single shared service object if you wanted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法