Skip to content

Commit

Permalink
issue #106: work in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilsk committed Oct 5, 2017
1 parent 422966f commit 64731a0
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions example_user_rate_limit_test.go
@@ -0,0 +1,52 @@
package semaphore_test

import (
"context"
"sync"

"github.com/kamilsk/semaphore"
)

type User int

type Config struct {
DefaultUser User
DefaultCapacity int
}

func Example_userRateLimitation() {
var (
mx sync.RWMutex
capacity map[User]int = make(map[User]int)
limiters map[User]semaphore.Semaphore = make(map[User]semaphore.Semaphore)

config Config = Config{
DefaultUser: 0,
DefaultCapacity: 10,
}
)

_ = func(ctx context.Context) semaphore.Semaphore {
user, ok := ctx.Value("user").(User)
if !ok {
user = config.DefaultUser
}

mx.RLock()
sem, ok := limiters[user]
mx.RUnlock()

if !ok {
c, ok := capacity[user]
if !ok {
c = config.DefaultCapacity
}
sem = semaphore.New(c)

mx.Lock()
limiters[user] = sem
mx.Unlock()
}
return sem
}
}

0 comments on commit 64731a0

Please sign in to comment.