今天的这篇文章《特定路由的 Gorilla 中间件身份验证不起作用》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
问题内容
我正在为 api 编写一个 Http 路由器,有些路由需要身份验证,而有些则不需要。
我不想在每条路线上都要求身份验证,所以我将它们分开。
但是有一个问题:
post /account <--这是帐户注册端点,不需要身份验证
delete /account <--这确实需要身份验证才能删除当前帐户
我不知道如何正确分离它们,而且我目前尝试使两者的中间件不同的尝试也失败了:
package httpserver
import (
"log"
"net/http"
"httpServer/handlers"
"httpServer/middlewares"
"GitHub.com/gorilla/mux"
"github.com/justinas/alice"
)
func Init() {
log.Println("Initializing http routes...")
defaultmiddlewares := alice.New(middlewares.Logger, middlewares.Recover)
authmiddlewares := alice.New(middlewares.Authenticator)
var mainRouter = mux.NewRouter()
var authRouter = mux.NewRouter()
// No auth required to call this
mainRouter.HandleFunc("/health", handlers.HealthGet).Methods("GET") // Get API health
// authrouter should be a extension of main router (i think)
mainRouter.Handle("/", authmiddlewares.Then(authRouter))
// Authentication is not required for this
mainRouter.HandleFunc("/account", handlers.AccountPost).Methods("POST") // Create an account
// Authentication is required for this
authRouter.HandleFunc("/account", handlers.AccountDelete).Methods("DELETE") // Delete my account
// websocket endpoint:
authRouter.HandleFunc("/ws", handlers.UpgradeWs)
authRouter.HandleFunc("/ws/", handlers.UpgradeWs) // If i dont add this it doesnt work??
// ReGISter mainRouter
http.Handle("/", defaultmiddlewares.Then(mainRouter))
}
调用 get /health 就可以了: 但对 delete /account 的调用失败,并显示 404 not found:
(也在 init() 函数末尾附近,我注册了一个 WEBSocket 端点,出于某种原因,如果我不注册这两个端点,它就无法连接?)
正确答案
您初始化了两个路由器 mainrouter 和 authrouter ,并且仅启动 mainrouter。 delete /account 绑定到 authrouter 。那就是没有启动和监听。这就是 404 出现的原因。
您可以将自定义中间件实现编写为 gorilla/mux Middleware interface 并与 gorilla/mux 路由器一起使用。示例代码如下
func Init() {
log.Println("Initializing http routes...")
r := mux.NewRouter()
middleware := Middleware{
// inject any dependency if you need
}
r.Use(middleware.MiddlewareFunc)
// No auth required to call this
r.HandleFunc("/health", handlers.HealthGet).Methods("GET") // Get API health
// authrouter should be a extension of main router (i think)
r.Handle("/", authmiddlewares.Then(authRouter))
// Authentication is not required for this
r.HandleFunc("/account", handlers.AccountPost).Methods("POST") // Create an account
// Authentication is required for this
r.HandleFunc("/account", handlers.AccountDelete).Methods("DELETE") // Delete my account
http.ListenAndServe(":8080", r)
}
// Middleware your custom middleware implementation
type Middleware struct {}
func (m Middleware) MiddlewareFunc(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// you can check request method and paths and you can do authentications here
//eg := method = DELETE and path = /account, do authentication
handler.ServeHTTP(w, r)
})
}
今天关于《特定路由的 Gorilla 中间件身份验证不起作用》的内容就介绍到这里了,是不是学起来一目了然!