package controller import ( "gin-demo/response" "gin-demo/util" "os" "strings" "github.com/gin-gonic/gin" "github.com/spf13/viper" ) type CategoryController struct { } func MarkdownLoad() CategoryController { return CategoryController{} } func (c CategoryController) Show(ctx *gin.Context) { urlPath := "" urlPath = ctx.Request.URL.Path //fmt.Println(urlPath) if strings.HasPrefix(urlPath, "/static") { if _, err := os.Stat("." + urlPath); err == nil { ctx.File("." + urlPath) ctx.Header("Cache-Control", "public,s-maxage=300,max-age=31536000") ctx.Abort() // file found, stop the handler chain return } } rootDir := viper.GetString("dir.root") path := rootDir + urlPath pathInfo, err := os.Stat(path) listResult := util.GetFileList(path) if err != nil { response.Fail(ctx, gin.H{}) } if pathInfo.IsDir() { if urlPath == "/" { path = path + viper.GetString("dir.main") } htmlContext := util.GetDirStr(path) //fmt.Println(htmlContext) response.Success(ctx, gin.H{"title": pathInfo.Name(), "htmlContext": htmlContext, "list": listResult}) } else if strings.HasSuffix(pathInfo.Name(), ".md") { // 后缀判断 htmlContext := util.GetMdStr(path) //fmt.Println(htmlContext) title := pathInfo.Name() title = strings.ReplaceAll(title, ".md", "") response.Success(ctx, gin.H{"title": title, "htmlContext": htmlContext, "list": listResult}) } else { ctx.Header("Cache-Control", "public,s-maxage=300,max-age=31536000") ctx.File(path) ctx.Abort() } }