42 lines
1.6 KiB
Go
42 lines
1.6 KiB
Go
package router
|
|
|
|
import (
|
|
"github.com/gorilla/csrf"
|
|
"github.com/gorilla/mux"
|
|
"net/http"
|
|
"picgo/configs"
|
|
"picgo/handler"
|
|
"picgo/middleware"
|
|
)
|
|
|
|
func InitRouter() *mux.Router {
|
|
var secure bool
|
|
if configs.Settings.Server.Environment == "dev" {
|
|
secure = false
|
|
} else {
|
|
secure = true
|
|
}
|
|
// 设置CSRF保护
|
|
CSRF := csrf.Protect(
|
|
[]byte(configs.Settings.Server.SessionsKey),
|
|
csrf.Secure(secure), // 在开发环境中禁用HTTPS
|
|
csrf.RequestHeader("X-CSRF-Token"),
|
|
)
|
|
// 创建新的路由器
|
|
r := mux.NewRouter()
|
|
// 不需要鉴权路由
|
|
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", handler.StaticHandler()))
|
|
r.HandleFunc("/login", handler.LoginHandler).Methods(http.MethodGet, http.MethodPost) // 登录
|
|
r.HandleFunc("/captcha", handler.CaptchaHandler).Methods(http.MethodGet) // 验证码接口
|
|
// 需要鉴权路由
|
|
r.Handle("/", middleware.LoginMiddleware(http.HandlerFunc(handler.IndexHandler))).Methods(http.MethodGet) // 后台首页
|
|
r.Handle("/domain", middleware.LoginMiddleware(http.HandlerFunc(handler.DomainHandler))).Methods(http.MethodGet) // 域名管理
|
|
r.Handle("/user", middleware.LoginMiddleware(http.HandlerFunc(handler.UserHandler))).Methods(http.MethodGet) // 用户管理
|
|
r.Handle("/picture", middleware.LoginMiddleware(http.HandlerFunc(handler.PictureHandler))).Methods(http.MethodGet) // 图片管理
|
|
r.Handle("/api/v1/upload", middleware.LoginMiddleware(http.HandlerFunc(handler.UploadFileHandler))).Methods(http.MethodPost) // 图片上传接口
|
|
// 应用 CORS CSRF 中间件
|
|
http.Handle("/", middleware.CorsMiddleware(CSRF(r)))
|
|
|
|
return r
|
|
}
|