picgo/router/router.go

43 lines
1.1 KiB
Go
Raw Normal View History

2024-07-11 21:25:58 +08:00
package router
import (
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
2024-07-11 21:25:58 +08:00
"net/http"
"picgo/configs"
2024-07-11 21:25:58 +08:00
"picgo/handler"
"picgo/middleware"
2024-07-11 21:25:58 +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-07-11 21:25:58 +08:00
// 创建新的路由器
r := mux.NewRouter()
// 处理静态文件
//staticDir := "static"
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", handler.StaticHandler()))
r.HandleFunc("/login", handler.LoginHandler)
r.HandleFunc("/captcha", handler.CaptchaHandler)
r.HandleFunc("/settings", handler.SettingsHandler)
r.HandleFunc("/profile", handler.ProfileHandler)
r.HandleFunc("/api/v1/upload", handler.UploadFileHandler)
// 路由鉴权
r.Handle("/", middleware.LoginMiddleware(http.HandlerFunc(handler.IndexHandler))).Methods(http.MethodGet)
// 应用 CORS 中间件
http.Handle("/", middleware.CorsMiddleware(CSRF(r)))
return r
2024-07-11 21:25:58 +08:00
}