瀏覽代碼

fix: render description as HTML when rendering message (close #42)

JustSong 2 年之前
父節點
當前提交
89e7a10d20
共有 4 個文件被更改,包括 22 次插入13 次删除
  1. 2 6
      channel/email.go
  2. 1 1
      common/public/message.html
  3. 12 0
      common/utils.go
  4. 7 6
      controller/message.go

+ 2 - 6
channel/email.go

@@ -1,9 +1,7 @@
 package channel
 
 import (
-	"bytes"
 	"errors"
-	"github.com/yuin/goldmark"
 	"message-pusher/common"
 	"message-pusher/model"
 )
@@ -17,12 +15,10 @@ func SendEmailMessage(message *model.Message, user *model.User) error {
 		subject = message.Title
 	}
 	if message.Content != "" {
-		var buf bytes.Buffer
-		err := goldmark.Convert([]byte(message.Content), &buf)
+		var err error
+		message.HTMLContent, err = common.Markdown2HTML(message.Content)
 		if err != nil {
 			common.SysLog(err.Error())
-		} else {
-			message.HTMLContent = buf.String()
 		}
 	}
 	return common.SendEmail(subject, user.Email, message.HTMLContent)

+ 1 - 1
common/public/message.html

@@ -19,7 +19,7 @@
                         <span class="line">发布于:<span class="tag is-light">{{.time}}</span></span>
                     </div>
                     <blockquote>
-                        <p>{{.description}}</p>
+                        {{.description | unescape}}
                     </blockquote>
                     {{.content | unescape}}
                 </article>

+ 12 - 0
common/utils.go

@@ -1,8 +1,10 @@
 package common
 
 import (
+	"bytes"
 	"fmt"
 	"github.com/google/uuid"
+	"github.com/yuin/goldmark"
 	"html/template"
 	"log"
 	"net"
@@ -139,3 +141,13 @@ func Max(a int, b int) int {
 		return b
 	}
 }
+
+func Markdown2HTML(markdown string) (HTML string, err error) {
+	var buf bytes.Buffer
+	err = goldmark.Convert([]byte(markdown), &buf)
+	if err != nil {
+		return fmt.Sprintf("Markdown 渲染出错:%s", err.Error()), err
+	}
+	HTML = buf.String()
+	return
+}

+ 7 - 6
controller/message.go

@@ -1,11 +1,9 @@
 package controller
 
 import (
-	"bytes"
 	"encoding/json"
 	"fmt"
 	"github.com/gin-gonic/gin"
-	"github.com/yuin/goldmark"
 	"message-pusher/channel"
 	"message-pusher/common"
 	"message-pusher/model"
@@ -173,13 +171,16 @@ func RenderMessage(c *gin.Context) {
 		c.Status(http.StatusNotFound)
 		return
 	}
+	if message.Description != "" {
+		message.Description, err = common.Markdown2HTML(message.Description)
+		if err != nil {
+			common.SysLog(err.Error())
+		}
+	}
 	if message.Content != "" {
-		var buf bytes.Buffer
-		err := goldmark.Convert([]byte(message.Content), &buf)
+		message.HTMLContent, err = common.Markdown2HTML(message.Content)
 		if err != nil {
 			common.SysLog(err.Error())
-		} else {
-			message.HTMLContent = buf.String()
 		}
 	}
 	c.HTML(http.StatusOK, "message.html", gin.H{