Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorilla mux custom middleware

Tags:

go

gorilla

I am using gorilla mux for manage routing. What I am missing is to integrate a middleware between every request.

For example

package main  import (     "fmt"     "github.com/gorilla/mux"     "log"     "net/http"     "strconv" )  func HomeHandler(response http.ResponseWriter, request *http.Request) {      fmt.Fprintf(response, "Hello home") }  func main() {      port := 3000     portstring := strconv.Itoa(port)      r := mux.NewRouter()     r.HandleFunc("/", HomeHandler)     http.Handle("/", r)      log.Print("Listening on port " + portstring + " ... ")     err := http.ListenAndServe(":"+portstring, nil)     if err != nil {         log.Fatal("ListenAndServe error: ", err)     } } 

Every incoming request should pass through the middleware. How can I integrate here a midleware?

Update

I will use it in combination with gorilla/sessions, and they say:

Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:

How can I prevent this scenario?

like image 886
softshipper Avatar asked Oct 05 '14 16:10

softshipper


People also ask

What is Gorilla mux used for?

Gorilla Mux provides functionalities for matching routes, serving static files, building single-page applications (SPAs), middleware, handling CORS requests, and testing handlers. This tutorial will walk you through using the Gorilla Mux package as a router for your applications.

Is Gorilla mux a framework?

gorilla/mux is a powerful URL router and dispatcher. gorilla/reverse produces reversible regular expressions for regexp-based muxes. gorilla/rpc implements RPC over HTTP with codec for JSON-RPC.

What is mux Vars?

The name mux stands for "HTTP request multiplexer". Like the standard http. ServeMux, mux. Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.


1 Answers

Just create a wrapper, it's rather easy in Go:

func HomeHandler(response http.ResponseWriter, request *http.Request) {      fmt.Fprintf(response, "Hello home") }  func Middleware(h http.Handler) http.Handler {     return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {         log.Println("middleware", r.URL)         h.ServeHTTP(w, r)     }) } func main() {     r := mux.NewRouter()     r.HandleFunc("/", HomeHandler)     http.Handle("/", Middleware(r)) } 
like image 109
OneOfOne Avatar answered Oct 04 '22 21:10

OneOfOne