Skip to content

Instantly share code, notes, and snippets.

@jharlap
Last active April 27, 2016 04:13
Show Gist options
  • Save jharlap/2efd687f456394f5783cf8bff74d5409 to your computer and use it in GitHub Desktop.
Save jharlap/2efd687f456394f5783cf8bff74d5409 to your computer and use it in GitHub Desktop.
Non-httprouter routers and how to write a response time tracker middleware for them

See the section in each example labelled as MAGIC for how to get the route pattern which matched the url path for each router.

package main
import (
"log"
"net/http"
"time"
goji "goji.io"
"goji.io/middleware"
"goji.io/pat"
"golang.org/x/net/context"
)
func main() {
m := goji.NewMux()
m.HandleFuncC(pat.Get("/ordereditems/:key"), fake)
m.HandleFuncC(pat.Post("/ordereditems/:key"), fake)
m.HandleFuncC(pat.Get("/ordereditems/:key/items"), fake)
m.HandleFuncC(pat.Post("/ordereditems/:key/items"), fake)
m.HandleFuncC(pat.Put("/ordereditems/:key/items/:itemID/position"), fake)
m.UseC(tracker)
log.Println(http.ListenAndServe(":2380", m))
}
func tracker(next goji.Handler) goji.Handler {
service := "myService"
f := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTPC(ctx, w, r)
// THIS IS THE MAGIC
p := middleware.Pattern(ctx)
// END MAGIC
log.Printf("track service %s path %s time %s", service, p, time.Since(start))
}
return goji.HandlerFunc(f)
}
func fake(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func main() {
m := mux.NewRouter()
m.KeepContext = true // necessary for mux.CurrentRoute to work in middleware
s := m.PathPrefix("/ordereditems").Subrouter()
s.HandleFunc("/{key}", fake).Methods("GET")
s.HandleFunc("/{key}", fake).Methods("POST")
s.HandleFunc("/{key}/items", fake).Methods("POST", "GET")
s.HandleFunc("/{key}/items/{itemID}/position", fake).Methods("PUT")
log.Println(http.ListenAndServe(":2380", tracker(m)))
}
func tracker(next http.Handler) http.Handler {
service := "myService"
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
// THIS IS THE MAGIC
route := mux.CurrentRoute(r)
if route == nil {
return
}
p, err := route.GetPathTemplate()
if err != nil {
p = "unknown_path"
}
// END MAGIC
log.Printf("track service %s path %s time %s", service, p, time.Since(start))
})
}
func fake(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment