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?

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