【问题标题】:How to return html on Gin?如何在 Gin 上返回 html?
【发布时间】:2017-05-19 22:24:15
【问题描述】:

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

GET("/") 函数上的 c.HTML 函数需要渲染一个模板。

但在POST("/markdown") 上,我已经在字符串上呈现了该 HTML。

我怎样才能在杜松子酒上退货?

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")
}

【问题讨论】:

  • 可以在html模板中显示markdown内容
  • 好的 @Bhavanna,但我正在尝试实现“使用 Go 构建 Web 应用程序”一书中的示例
  • 您想在发布请求时做什么?你期待什么输出?

标签: html go go-gin


【解决方案1】:

您可以将处理后的降价字节数组返回为RAW Data,并将内容类型设置为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)
    })

【讨论】:

    【解决方案2】:

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

    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>"))
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多