How to rewrite code and apply middleware gorilla mux routes

188 views
Skip to first unread message

afriyie...@gmail.com

unread,
Apr 3, 2019, 4:28:55 AM4/3/19
to golang-nuts
Hi

I have this working main function code and would like to rewrite it such that the middleware "validateToken" would be applied
to all my gorilla mux routes.
Please attached is the file containg the working code.

What i would like to do is to use the handler function   

http.HandleFunc("/protected", validateToken(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, I'm protected"
outside the main function as
func protecteduri(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, I'm protected"))
}

and apply the middleware function "validateToken" to all my gorilla mux routes so that the token used to request can be validated. The routes 
type Route struct {
Name        string
Method      string
Pattern     string
HandlerFunc http.HandlerFunc
}

type Routes []Route

func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)

router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}

return router
}

func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}

var routes = Routes{
{
"Index",
"GET",
"/",
Index,
},

{
"protecteduri",
strings.ToUpper("Get"),
"/protected",
protecteduri,
},

{
"AccessTokenRequest",
strings.ToUpper("Post"),
"/oauth2/token",
AccessTokenRequest,
},
}

 Can anyone help?


afriyie...@gmail.com

unread,
Apr 3, 2019, 5:13:41 AM4/3/19
to golang-nuts
Sorry please attacted is the file 
main.go

afriyie...@gmail.com

unread,
Apr 3, 2019, 5:14:24 AM4/3/19
to golang-nuts


On Wednesday, April 3, 2019 at 11:28:55 AM UTC+3, afriyie...@gmail.com wrote:
Reply all
Reply to author
Forward
0 new messages