dongzhong9055 2019-08-25 12:46
浏览 300

Golang Restful API中的全局变量

We have an post rest api in golang created using net/http package and used gorilla/mux as request router and dispatcher. The api takes an object as input, lets say x and set it as a global variable and through its course of action the api uses values within this object and provides result.

Now everything was working fine until we found out that when multiple requests hits the api other request modifies the global object. For eg, let say I have sent request with x = 5 and before this request ends another request came in and set x = 10, which causes multiple result for first request one with x=5 and other with x=10.

My query is, can I set a global variable per request? I understand session seems a straight forward answer but is it correct since its a REST api and it should be stateless, also if it is correct how can I do it in golang? What should be used as unique key in session? Also, if session is not the way to go then what is correct approach?

  • 写回答

1条回答 默认 最新

  • dqwnxdhb88531 2019-08-26 03:35
    关注

    One of the reasons the context package exists is to make it easy to pass request-scoped values, try it out. You will have to pass the context to your methods, but that seems to be a much better way than using some package level variable and a mutex for synchronization.

    https://blog.golang.org/context

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站