如何在Go中使用mux(gorilla)进行路由组合?

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月4日 23:00:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75345954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定