A goroutine limiter for Go
Branch: master
Clone or download
Latest commit fcddc63 Dec 20, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
LICENSE first commit Dec 19, 2018
README.md first commit Dec 19, 2018
limiter.go Use buffered channel #1 Dec 20, 2018
limiter_test.go first commit Dec 19, 2018
logo.png first commit Dec 19, 2018

README.md

GJSON
GoDoc

Limiter is a Golang library for limiting work coming from any number of goroutines. This is useful when you need limit the maximum number of concurrent calls to a specific operation.

Install

go get github.com/tidwall/limiter

Example

package main

import (
	"io/ioutil"
	"net/http"

	"github.com/tidwall/limiter"
)

func main() {

	// Create a limiter for a maximum of 10 concurrent operations
	l := limiter.New(10)

	http.HandleFunc("/work", func(w http.ResponseWriter, r *http.Request) {
		input, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "Internal error", http.StatusInternalServerError)
		}
		defer r.Body.Close()

		var result []byte
		func() {
			l.Begin()
			defer l.End()
			// Do some intensive work here. It's guaranteed that only a maximum of ten
			// of these operations will run at the same time.
			result = []byte("rad!")
		}()

		w.Write(result.([]byte))
	})

	http.ListenAndServe(":8080", nil)
}

Contact

Josh Baker @tidwall

License

Limiter source code is available under the MIT License.