Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can you use this per path only? #45

Open
neumachen opened this issue Jan 16, 2018 · 1 comment
Open

Can you use this per path only? #45

neumachen opened this issue Jan 16, 2018 · 1 comment

Comments

@neumachen
Copy link

How would you use this if you want to use a middle per route/path?

@FlavorJ
Copy link

FlavorJ commented Jul 29, 2019

This (taken from example) adds the chain to DefaultServeMux for a path. You can use a ServeMux, or you can write your own handler that processes the path.

package main

import (
    "net/http"
    "time"

    "github.com/throttled/throttled"
    "github.com/justinas/alice"
    "github.com/justinas/nosurf"
)`

func timeoutHandler(h http.Handler) http.Handler {
    return http.TimeoutHandler(h, 1*time.Second, "timed out")
}

func myApp(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello world!"))
}

func main() {
    th := throttled.Interval(throttled.PerSec(10), 1, &throttled.VaryBy{Path: true}, 50)
    myHandler := http.HandlerFunc(myApp)

    chain := alice.New(th.Throttle, timeoutHandler, nosurf.NewPure).Then(myHandler)
    http.Handle("/", chain) // Path "/" registers chain to DefaultServeMux for all unregistered paths
    http.ListenAndServe(":8000", nil) // nil means to use DefaultServeMux
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants