2

I have the following code in which I have two mux, one for unauthenticated routes (r) and another for authenticated routes (chain). I want to combine these two and serve.


package main

import (
    "ekart.com/authentication_service/models"

    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/justinas/alice"
)

func main() {
    var JSON_SECRET []byte = []byte("TZWfMhBEuyzsc2e52wQQaDxfBriktka9GR4BhBtH9PhXi6XHwyaaaUyxBc-yd1RtYKsiFAGXZcBJuQ6ML5UGBEEx72Qhw6Q-192msUDwMHxT3Scz5wWnk--Bp8wotvu7FS2-v88cvC52e1lfG8mr60dGu7kg-jzcRa5cDTfR4KMQIAD6lO1H3J6f48u46gLjQtzOLPH9yjx0mqVtGWmaizGMQE7NdrhHH5ZlMuuj-A6lZRjf2VZKxUiFFWmfnVMhPVh-wpOybMaFzhUjm-RWXQ-E6cCeI-sBzcu5ZJ8aZVnYPc1Inc5RJ9R5rKQblctxHt5QCYlxiFHb63aO36ZS0Q")
    var DSN string = "root:toor@tcp(localhost:3306)/ekart_auth?charset=utf8&parseTime=True&loc=Local"
    app := Config{secret: JSON_SECRET}
    app.NewDatabaseConnection(DSN)
    app.DB.AutoMigrate(&models.User{})

    r := mux.NewRouter()
    r.HandleFunc("/login", app.Login).Methods("POST")
    r.HandleFunc("/register", app.Register).Methods("POST")
    
    authmux := mux.NewRouter()
    authmux.HandleFunc("/onlyauth", app.OnlyIfAuthenticated).Methods("GET")
    chain := alice.New(app.Authenticate).Then(authmux)

    log.Print(fmt.Sprintf("Starting Server on port %d", 8080))
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", 8080), r))

}

I have tried this way but that didn't work.

Also I tried from here

s := r.PathPrefix("/auth").Subrouter()
s.HandleFunc("/", chain.ServeHTTP)

But this also doesn't work.

It would be better if the answer doesn't require me to create a subpath but ok if I have to do that.

Sushant
  • 123
  • 8
  • 1
    Be aware that the [gorilla/mux](https://github.com/gorilla/mux#gorillamux) is no longer maintained. – jub0bs Feb 04 '23 at 19:09

1 Answers1

1

You can combine both r and chain routers by using the Use method of the mux package. You can use Use to add a middleware to a route, and since chain has a middleware app.Authenticate using alice.New, you can add it to the r router as a middleware.

func main() {
// ...

r := mux.NewRouter()
r.HandleFunc("/login", app.Login).Methods("POST")
r.HandleFunc("/register", app.Register).Methods("POST")

authmux := mux.NewRouter()
authmux.HandleFunc("/onlyauth", app.OnlyIfAuthenticated).Methods("GET")
chain := alice.New(app.Authenticate).Then(authmux)

r.Use(app.Authenticate)
r.PathPrefix("/auth").Handler(chain)

log.Print(fmt.Sprintf("Starting Server on port %d", 8080))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", 8080), r)) 

}

Now all routes under /auth will have the app.Authenticate middleware applied to them.

Jamal Kaksouri
  • 1,684
  • 15
  • 22