Created
October 5, 2018 04:45
-
-
Save chonlatee/5c4b6f689167ebe6c8d458cb0c205834 to your computer and use it in GitHub Desktop.
middleware separate route in golang (use mux and negroni )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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