Skip to content

Instantly share code, notes, and snippets.

@chonlatee
Created October 5, 2018 04:45
Show Gist options
  • Save chonlatee/5c4b6f689167ebe6c8d458cb0c205834 to your computer and use it in GitHub Desktop.
Save chonlatee/5c4b6f689167ebe6c8d458cb0c205834 to your computer and use it in GitHub Desktop.
middleware separate route in golang (use mux and negroni )
package main
import (
"fmt"
"log"
"net/http"
"github.com/urfave/negroni"
"github.com/gorilla/mux"
)
func MyMiddleware1(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
log.Println("Before My Middleware1")
next(w, r)
log.Println("After My Middleware1")
}
func MyMiddleware2(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
log.Println("Before My Middleware2")
next(w, r)
log.Println("After My Middleware2")
}
func MyMiddleware3(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
log.Println("Before My Middleware3")
next(w, r)
log.Println("After My Middleware3")
}
func main() {
r := mux.NewRouter().StrictSlash(false)
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Home index")
})
authBase := mux.NewRouter()
r.PathPrefix("/").Handler(negroni.New(
negroni.HandlerFunc(MyMiddleware1),
negroni.Wrap(authBase),
)).Path("/profile").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "/auth/profile")
})
notAuth := mux.NewRouter()
r.PathPrefix("/").Handler(negroni.New(
negroni.NewLogger(),
negroni.HandlerFunc(MyMiddleware2),
negroni.Wrap(notAuth),
)).Path("/login")
http.ListenAndServe(":3000", r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment