concurrentlimiter

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2019 License: Apache-2.0 Imports: 5 Imported by: 0

README

cod-concurrent-limiter

Build Status

Concurrent limiter for cod. It support to get lock value from five way. Client IP, QueryString, Request Header, Route Params and Post Body.

  • IP The key's name is :ip
  • QueryString The key's name has prefix q:
  • Request Header The key's name has prefix h:
  • Route Params The key's name has prefix p:
  • Post Body The other's key
package main

import (
	"bytes"
	"sync"
	"time"

	"github.com/vicanso/cod"

	concurrentLimiter "github.com/vicanso/cod-concurrent-limiter"
)

func main() {

	d := cod.New()
	d.Keys = []string{
		"cuttlefish",
	}
	m := new(sync.Map)
	limit := concurrentLimiter.New(concurrentLimiter.Config{
		Keys: []string{
			":ip",
			"h:X-Token",
			"q:type",
			"p:id",
			"account",
		},
		Lock: func(key string, c *cod.Context) (success bool, unlock func(), err error) {
			_, loaded := m.LoadOrStore(key, true)
			// the key not exists
			if !loaded {
				success = true
				unlock = func() {
					m.Delete(key)
				}
			}
			return
		},
	})

	d.POST("/login", limit, func(c *cod.Context) (err error) {
		time.Sleep(3 * time.Second)
		c.BodyBuffer = bytes.NewBufferString("hello world")
		return
	})

	d.ListenAndServe(":7001")
}

Documentation

Index

Constants

View Source
const (

	// ErrCategory concurrent limiter error category
	ErrCategory = "cod-concurrent-limiter"
)

Variables

This section is empty.

Functions

func New

func New(config Config) cod.Handler

New create a concurrent limiter middleware

Types

type Config

type Config struct {
	// Keys keys for generate lock id
	Keys []string
	// Lock lock function
	Lock    Lock
	Skipper cod.Skipper
}

Config concurrent limiter config

type Lock

type Lock func(string, *cod.Context) (bool, func(), error)

Lock lock the key

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL