2024-07-11 21:25:58 +08:00
|
|
|
package router
|
|
|
|
|
|
|
|
import (
|
2024-07-13 20:33:20 +08:00
|
|
|
"github.com/gorilla/csrf"
|
|
|
|
"github.com/gorilla/mux"
|
2024-07-11 21:25:58 +08:00
|
|
|
"net/http"
|
2024-07-13 20:33:20 +08:00
|
|
|
"picgo/configs"
|
2024-07-11 21:25:58 +08:00
|
|
|
"picgo/handler"
|
2024-07-13 20:33:20 +08:00
|
|
|
"picgo/middleware"
|
2024-07-11 21:25:58 +08:00
|
|
|
)
|
|
|
|
|
2024-07-13 20:33:20 +08:00
|
|
|
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"),
|
|
|
|
)
|
2024-08-06 20:37:34 +08:00
|
|
|
|
2024-07-11 21:25:58 +08:00
|
|
|
// 创建新的路由器
|
2024-07-13 20:33:20 +08:00
|
|
|
r := mux.NewRouter()
|
2024-07-16 20:32:22 +08:00
|
|
|
// 不需要鉴权路由
|
2024-08-06 20:37:34 +08:00
|
|
|
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", handler.StaticHandler())) // 静态资源路由
|
|
|
|
r.HandleFunc("/login", handler.LoginPageHandler).Methods(http.MethodGet) // 登录页面
|
|
|
|
r.HandleFunc("/api/v1/login", handler.LoginApiHandler).Methods(http.MethodPost) // 登录接口
|
|
|
|
r.HandleFunc("/captcha", handler.CaptchaApiHandler).Methods(http.MethodGet) // 验证码接口
|
|
|
|
// 需要鉴权页面路由
|
|
|
|
r.Handle("/", middleware.LoginMiddleware(http.HandlerFunc(handler.IndexPageHandler))).Methods(http.MethodGet) // 后台首页
|
|
|
|
r.Handle("/domain", middleware.LoginMiddleware(http.HandlerFunc(handler.DomainPageHandler))).Methods(http.MethodGet) // 域名管理
|
|
|
|
r.Handle("/user", middleware.LoginMiddleware(http.HandlerFunc(handler.UserPageHandler))).Methods(http.MethodGet) // 用户管理
|
|
|
|
r.Handle("/picture", middleware.LoginMiddleware(http.HandlerFunc(handler.PicturePageHandler))).Methods(http.MethodGet) // 图片管理
|
|
|
|
// 需要鉴权接口路由
|
|
|
|
r.Handle("/api/v1/upload", middleware.LoginMiddleware(http.HandlerFunc(handler.UploadFileApiHandler))).Methods(http.MethodPost) // 图片上传接口
|
|
|
|
r.Handle("/api/v1/user/create", middleware.LoginMiddleware(http.HandlerFunc(handler.UserCreateApiHandler))).Methods(http.MethodPost) // 新增用户
|
2024-08-09 20:30:35 +08:00
|
|
|
r.Handle("/api/v1/user/page", middleware.LoginMiddleware(http.HandlerFunc(handler.UserPageApiHandler))).Methods(http.MethodPost) // 分页查询用户
|
2024-08-06 20:37:34 +08:00
|
|
|
|
2024-07-16 20:32:22 +08:00
|
|
|
// 应用 CORS CSRF 中间件
|
2024-07-13 20:33:20 +08:00
|
|
|
http.Handle("/", middleware.CorsMiddleware(CSRF(r)))
|
|
|
|
|
|
|
|
return r
|
2024-07-11 21:25:58 +08:00
|
|
|
}
|