Skip to content

Instantly share code, notes, and snippets.

@whargrove
Created June 16, 2019 03:06
Show Gist options
  • Save whargrove/7787a0bc91d7f267aa9eb5645d690fb8 to your computer and use it in GitHub Desktop.
Save whargrove/7787a0bc91d7f267aa9eb5645d690fb8 to your computer and use it in GitHub Desktop.
Better token refresher
package main
import (
"log"
"math/rand"
"time"
"github.com/google/uuid"
)
var token string
func main() {
log.Println("Starting token worker")
tokenReceiver := make(chan string)
go tokenWorker(tokenReceiver)
for {
select {
case val := <-tokenReceiver:
log.Println("Received new AccessToken:", val)
token = val
}
}
}
func tokenWorker(tokenReceiver chan string) {
at := GetAccessToken()
log.Println("Sending new token to receiver")
tokenReceiver <- at.Token
log.Println("Sleeping for", at.ExpiresIn)
time.Sleep(at.ExpiresIn)
go tokenWorker(tokenReceiver)
}
// GetAccessToken creates a stub AccessToken
func GetAccessToken() *AccessToken {
u, _ := uuid.NewRandom()
return &AccessToken{
Token: u.String(),
ExpiresIn: time.Duration(rand.Int63n(5)) * time.Second,
}
}
// AccessToken represents a token that can be used to authenticate with a REST API
type AccessToken struct {
Token string
ExpiresIn time.Duration
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment