1 回答
TA贡献1786条经验 获得超13个赞
您初始化了两个路由器,并且只启动了 。 绑定到 。这不是开始和倾听。这就是404来的原因。mainRouterauthRouter mainRouterDELETE /accountauthRouter
您可以将自定义中间件实现写入大猩猩/多路复用器中间件接口,并与路由器一起使用。示例代码如下所示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)
})
}
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报