How it works...

This recipe takes care of storing and retrieving the contents of a token to/from a file. If it's a first run, it must execute the entire code exchange, but subsequent runs will reuse the access token, and, if one is available, it will refresh using the refresh token.

There is currently no way in this code to differentiate between users/tokens, but that could be accomplished with cookies as a key for a filename or a row in the database as well. Let's walk through what this code does:

  • The config.go file wraps the standard OAuth2 config. For every method that involves retrieving a token, we first check whether we have a valid token in local storage. If not, we retrieve one using the standard config and then store it.
  • The tokensource.go file implements our custom TokenSource interface, which pairs with Config. Similar to Config, we always first try to retrieve our token from a file; failing this, we set it with the new token.
  • The storage.go file is the storage interface used by Config and TokenSource. It only defines two methods and we also include a helper function to bootstrap the OAuth2 code-based flow similar to what we did in the previous recipe, but if a file with a valid token already exists, it will be used instead.
  • The filestorage.go file implements the storage interface. When we store a new token, we first truncate the file and write a JSON representation of the token struct. Otherwise, we decode the file and return token.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.196.211