alice icon indicating copy to clipboard operation
alice copied to clipboard

Can you use this per path only?

Open neumachen opened this issue 8 years ago • 1 comments

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

neumachen avatar Jan 16 '18 15:01 neumachen

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
}

FlavorJ avatar Jul 29 '19 22:07 FlavorJ