TransWikia.com

Does the value of global variable persist in multiple API calls

Stack Overflow Asked by Shubroto Shuvo on January 10, 2021

So I have done a lot of research and could not find a proper answer. This might be a bit long post so sorry for that. I am making a backend API using golang. I am using gingonic for routing and api stuffs.

There are 2 part of the service. Application and user. When lets say createAccount endpoint is called from the other micro service, it need to pass the user information and application token in body. Each application is like micro service that is registered to this micro service that I am building and have a unique token. If the token they pass matches then I will get the id of that row and use that to create an entry in user table which will have the id associate with it.

Now for every API call to this micro service, it is important that they are sending the valid token and that row id is needed to do all sort of functionality like login user, edit user info and so on as the each user is connected with that app id by foreign key. Currently, I wrote a middleware and when any api call is made I get row id and save it to a global variable and then when necessary I am using it in any part of the codebase.

Lets say if 5 multiple API call is made, will that global variable information will be persisted or for each call its brand new value? If it is persisted then what can I do to achieve the brand new of Global variable for every API call or if there are better approach can you please recommend it?

2 Answers

A global variable is not the answer here. It will be overwritten by each request as you suspected. Instead, the typical way to handle this situation is to have a context object that is created within the scope of the HTTP Request and passed to each method that requires knowledge of that context.

Correct answer by see sharper on January 10, 2021

One basic rule is to AVOID using the global variables, it is bad practices, you cannot manage the state and you are limited for testing and concurrency using.

In my mind come two basic solutions:

  1. Use context for this. In your handler, add the value in context and propagate this context by all your service calls. It is also useful for tracing if you are working with microservices, then you also should take a look for this. And in the place where you need the value from your global variable, do simple call: ctx.Value(YOUR_KEY) Take a look at the end of the page, you shouldn't use string as the key to context values.
  2. You can wrap your data in the struct with this variable value. For example:
type CreateReq struct {
    Token string // value from global variable
    User user
}

and use this Token in your services.

Answered by Vasile Razdalovschi on January 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP