package controller import ( "gin-demo/response" "gin-demo/util" "html/template" "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") message := template.HTML("") if "" != viper.GetString("message") { message = template.HTML(viper.GetString("message")) } 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, "message": message}) } 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, "message": message}) } else { ctx.Header("Cache-Control", "public,s-maxage=300,max-age=31536000") ctx.File(path) ctx.Abort() } }