我为API编写http路由器,有些路由需要身份验证,而有些则不需要。
我不想要求在每个路由上进行身份验证,所以我将它们分开。
但有一个问题:
POST /帐户< - 这是帐户注册终结点,不需要身份验证
删除 /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 /运行状况的调用刚刚好:
但是对 DELETE /account 的调用失败,并显示 404 未找到:
(同样在 Init() 函数的末尾,我注册了一个 websocket 端点,由于某种原因,如果我不注册这两个端点,它就无法连接?
开满天机
相关分类