douyuan4697 2017-01-05 11:31
浏览 2744
已采纳

如何在Gin上返回HTML?

I'm trying to render a HTML that's already on a string instead of rendering a template on Gin framework.

The c.HTML function on GET("/") function expects a template to be rendered.

But on POST("/markdown") I've rendered that HTML on a string already.

How can I return it on Gin?

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")
}
  • 写回答

1条回答 默认 最新

  • douyuan6490 2017-01-05 12:07
    关注

    You can return the processed markdown byte array as a RAW Data and set content-type as text/html; charset=utf-8

    This is how it may look like

    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)
        })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥50 vue router 动态路由问题