如何在 Gin 上 return html?

How to return html on Gin?

我正在尝试渲染已经在字符串上的 HTML,而不是在 Gin 框架上渲染模板。

GET("/") 函数上的 c.HTML 函数需要呈现模板。

但是在 POST("/markdown") 上我已经在字符串上渲染了 HTML。

如何在 Gin 上 return 它?

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/russross/blackfriday"
    "log"
    "net/http"
    "os"
)

func main() {

    router := gin.New()
    router.Use(gin.Logger())
    router.LoadHTMLGlob("templates/*.tmpl.html")

    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl.html", nil)
    })

    router.POST("/markdown", func(c *gin.Context) {
        body := c.PostForm("body")
        log.Println(body)
        markdown := blackfriday.MarkdownCommon([]byte(c.PostForm("body")))
        log.Println(markdown)
        // TODO: render markdown content on return
    })

    router.Run(":5000")
}

您可以return将处理后的markdown字节数组作为RAW Data并将content-type设置为text/html; charset=utf-8

这是它的样子

router.POST("/markdown", func(c *gin.Context) {
        body, ok := c.GetPostForm("body")
        if !ok {
            c.JSON(http.StatusBadRequest, "badrequest")
            return
        }
        markdown := blackfriday.MarkdownCommon([]byte(body))
        c.Data(http.StatusOK, "text/html; charset=utf-8", markdown)
    })

您还可以为内容类型使用常量:

const (
    ContentTypeBinary = "application/octet-stream"
    ContentTypeForm   = "application/x-www-form-urlencoded"
    ContentTypeJSON   = "application/json"
    ContentTypeHTML   = "text/html; charset=utf-8"
    ContentTypeText   = "text/plain; charset=utf-8"
)
c.Data(http.StatusOK, ContentTypeHTML, []byte("<html></html>"))

blackfriday.MarkdownCommon() 的输出转换为 template.HTML,例如:

markdown := blackfriday.MarkdownCommon([]byte(c.PostForm("body")))
c.HTML(http.StatusOK, "markdown.html", gin.H {
    "markdown": template.HTML(markdown),
})