How to return html on Gin?

22.3k views Asked by At

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

There are 3 answers

0
Sarath Sadasivan Pillai On BEST ANSWER

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)
    })
0
Ostap Brehin On

You can also use constants for content types:

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>"))
0
Mars On

Convert the output of blackfriday.MarkdownCommon() to template.HTML like:

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