100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-contrib/sessions/cookie"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var logger = logrus.New()
|
|
|
|
func init() {
|
|
// 配置日志格式
|
|
logger.SetFormatter(&logrus.JSONFormatter{})
|
|
logger.SetOutput(os.Stdout)
|
|
}
|
|
|
|
func main() {
|
|
// 初始化 Gin 引擎
|
|
r := gin.Default()
|
|
|
|
// 配置静态文件服务
|
|
r.Static("/assets", "./static/assets")
|
|
r.LoadHTMLGlob("templates/*")
|
|
|
|
// 配置 Session 中间件
|
|
store := cookie.NewStore([]byte("secret"))
|
|
r.Use(sessions.Sessions("mysession", store))
|
|
|
|
// 登录页面
|
|
r.GET("/login", func(c *gin.Context) {
|
|
c.HTML(http.StatusOK, "login.html", nil)
|
|
})
|
|
|
|
// 处理登录请求
|
|
r.POST("/login", func(c *gin.Context) {
|
|
username := c.PostForm("username")
|
|
password := c.PostForm("password")
|
|
|
|
// 简单的用户名密码校验
|
|
if username == "admin" && password == "password" {
|
|
session := sessions.Default(c)
|
|
session.Set("user", username)
|
|
session.Save()
|
|
c.Redirect(http.StatusFound, "/")
|
|
} else {
|
|
c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "Invalid credentials"})
|
|
}
|
|
})
|
|
|
|
// 权限校验中间件
|
|
authMiddleware := func(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
user := session.Get("user")
|
|
if user == nil {
|
|
c.Redirect(http.StatusFound, "/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
|
|
// 文档页面路由
|
|
r.Use(authMiddleware)
|
|
r.GET("/", func(c *gin.Context) {
|
|
// 记录访问痕迹
|
|
logAccess(c)
|
|
http.ServeFile(c.Writer, c.Request, "./static/index.html")
|
|
})
|
|
r.GET("/guide/:page", func(c *gin.Context) {
|
|
// 记录访问痕迹
|
|
logAccess(c)
|
|
page := c.Param("page")
|
|
http.ServeFile(c.Writer, c.Request, fmt.Sprintf("./static/guide/%s.html", page))
|
|
})
|
|
|
|
// 启动服务
|
|
r.Run(":8080")
|
|
}
|
|
|
|
// 记录访问痕迹
|
|
func logAccess(c *gin.Context) {
|
|
ip := c.ClientIP()
|
|
path := c.Request.URL.Path
|
|
method := c.Request.Method
|
|
timestamp := time.Now().Format(time.RFC3339)
|
|
|
|
logger.WithFields(logrus.Fields{
|
|
"ip": ip,
|
|
"path": path,
|
|
"method": method,
|
|
"timestamp": timestamp,
|
|
}).Info("Page accessed")
|
|
}
|