new: Add RSS Feed

This commit is contained in:
2024-12-19 12:13:56 +08:00
parent cbd6d07d52
commit 2a5d17676f
11 changed files with 95 additions and 40 deletions

View File

@@ -23,6 +23,8 @@ type MApp struct {
engine *gin.Engine
searcher *engine.Engine
RSS string
Posts []*model.MPost
IndexedPosts map[uint64]*model.MPost

View File

@@ -457,6 +457,9 @@ func (ma *MApp) UpdateBlogHandler(ctx *gin.Context) {
// parse post index
ma.loadPostIndex()
// parse rss
ma.RSS = ma.generateRSS()
log.Println("update blog success")
ctx.JSON(http.StatusOK, gin.H{"msg": "ok"})
}
@@ -485,3 +488,11 @@ func (ma *MApp) AboutHandler(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "about.html", resData)
}
func (ma *MApp) RSSHandler(ctx *gin.Context) {
if ma.RSS != "" {
ctx.String(http.StatusOK, ma.RSS)
} else {
ctx.String(http.StatusNotFound, "RSS Not Found")
}
}

View File

@@ -4,6 +4,7 @@ func (ma *MApp) loadRoutes() {
ma.engine.Use(ma.AuthMiddleware)
ma.engine.GET("/", ma.IndexHandler)
ma.engine.GET("/rss", ma.RSSHandler)
ma.engine.GET("/about", ma.AboutHandler)
ma.engine.GET("/search", ma.SearchHandler)
ma.engine.GET("/archive", ma.ArchiveHandler)

56
internal/mApp/mRss.go Normal file
View File

@@ -0,0 +1,56 @@
package mApp
import (
"fmt"
"log"
"strconv"
"time"
"github.com/gorilla/feeds"
)
func (ma *MApp) generateRSS() string {
layout := "2006-01-02 15:04:05"
now := time.Now()
feed := &feeds.Feed{
Created: now,
Title: ma.Config.MSite.Info.Title,
Link: &feeds.Link{Href: ma.Config.MSite.Info.Link},
Author: &feeds.Author{Name: ma.Config.MSite.Info.Author, Email: ma.Config.MSite.Info.Email},
Description: ma.Config.MSite.Info.Description,
}
count := 0
var items []*feeds.Item
for _, post := range ma.Posts {
if count >= ma.Config.MSite.Post.RecentPost.Number {
break
}
updated, err := time.Parse(layout, post.Date)
if err != nil {
log.Println("Error parsing updated time ", post.Date)
continue
}
item := &feeds.Item{
Title: post.Title,
Id: strconv.FormatUint(post.Index, 10),
Link: &feeds.Link{Href: fmt.Sprintf("%s/post/%s", ma.Config.MSite.Info.Link, post.HtmlHash)},
Author: &feeds.Author{Name: ma.Config.MSite.Info.Author, Email: ma.Config.MSite.Info.Email},
Updated: updated,
}
items = append(items, item)
count++
}
feed.Items = items
rss, err := feed.ToRss()
if err != nil {
log.Println("Error generating rss ", err)
}
return rss
}