英文:
How to combine mux (gorilla) in Go?
问题
我有以下代码,其中包含两个 mux,一个用于未经身份验证的路由(r),另一个用于经过身份验证的路由(chain)。我想将这两个合并并提供服务。
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))
}
我尝试了这种方法,但没有成功。
我还尝试了这里的方法:
s := r.PathPrefix("/auth").Subrouter()
s.HandleFunc("/", chain.ServeHTTP)
但这也没有成功。
如果答案不需要我创建子路径会更好,但如果必须这样做也可以。
英文:
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.
答案1
得分: 1
你可以使用mux包的Use方法将r和chain路由器结合起来。你可以使用Use方法将中间件添加到路由中,由于chain具有一个中间件app.Authenticate,你可以将其作为中间件添加到r路由器中。
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))
}
现在,所有在/auth下的路由都将应用app.Authenticate中间件。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论