Skip to content

Instantly share code, notes, and snippets.

@viggin543
Created October 6, 2021 18:17
Show Gist options
  • Save viggin543/3eea24b59f5cd38d9b35de8882d5a4c0 to your computer and use it in GitHub Desktop.
Save viggin543/3eea24b59f5cd38d9b35de8882d5a4c0 to your computer and use it in GitHub Desktop.
func (this *usersService) IsMagicLinkVerified(ctx context.Context, in *users.IsMagicLinkVerifiedRequest) (*users.IsMagicLinkVerifiedResponse, error) {
c, _ := context.WithDeadline(ctx, time.Now().Add(25*time.Second))
ticker := ImmediateTicker(c, time.Second)
for {
select {
case <-c.Done():
return &users.IsMagicLinkVerifiedResponse{Status: users.MagicLinkStatus_unknown}, nil
case <-ticker:
status, token := this.tokensRepo.IsMagicLinkVerified(in.SessionId)
if status != users.MagicLinkStatus_unknown {
return &users.IsMagicLinkVerifiedResponse{
Status: status,
Token: token,
}, nil
}
}
}
}
@viggin543
Copy link
Author

viggin543 commented Oct 6, 2021

a couple of interesting points

  • line 2 -> merging the HTTP context with a timeout
  • line 6 -> awaits to whichever ever event happens first, the timeout or the connection is closed ( say if load balancer closes it )
  • line 8 -> ticking every second and asking tokensRepo ( redis ) if a key exists
  • line 10 -> if status is unknown ( we still wait ) -> continue infinite loop
  • line 11 -> if the key exists in redis, return response

Notice, no Promises or Futures or any multi-threading communication.
this is 100% async, every time the goroutine is awaiting ( say between the ticks ) No thread is blocked.

I think this is super cool !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment