justinas / alice

Painless middleware chaining for Go

Home Page:https://godoc.org/github.com/justinas/alice

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can you use this per path only?

neumachen opened this issue · comments

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

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
}