dqyin0101 2018-11-04 21:55
浏览 145
已采纳

优雅地处理gin-gonic中的模板渲染错误

I'm learning Go and using gin-gonic for a web application. I'm trying to recover gracefully from template errors and haven't been able to figure out how to buffer output or redirect properly to achieve this.

With this code:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.New()
    g.LoadHTMLGlob("templates/*")
    g.Use(func(c *gin.Context) {
        defer func() {
            if err := recover(); err != nil {
                c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
            }
        }()

        c.Next()
    })
    g.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{"var": 4})
    })
    g.Run(":80")
}

where templates/index.tmpl is

Before
<br>
Bad: {{.var.x}}
<br>
After

and templates/error.tmpl is

Oops! We encountered an error.

when I load my page, I see

Before
Bad: Oops! We encountered an error.

and the response code ends up being 200. I'd prefer to cleanly catch the error so that the only thing displayed to the user is

Oops! We encountered an error.

the response code comes out as 500, and the error gets logged on the server for later investigation.

What's the best way within gin to catch template errors without showing partial output to the user? I've seen several examples of accomplishing this with buffering using the built-in net/http stuff, but haven't been able to find anything for a good way to handle it in gin.

Edited with solution

Building off of @big pigeon's comments on the accepted answer, I ended up executing the template myself into a buffer and using c.Data() to display it if there were no errors. This still seems less than ideal since it bypasses features like multitemplate's ability to dynamically reload a parsed template at runtime in dev builds, but it works. The updated proof-of-concept code looks like:

package main

import (
    "bytes"
    "html/template"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.New()
    g.LoadHTMLGlob("templates/*")
    g.Use(func(c *gin.Context) {
        defer func() {
            if err := recover(); err != nil {
                c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
            }
        }()

        c.Next()
    })
    g.GET("/", func(c *gin.Context) {
        if tmpl, err := template.ParseFiles("templates/index.tmpl"); err != nil {
            panic(err)
        } else {
            buf := &bytes.Buffer{}
            if err = tmpl.Execute(buf, gin.H{"var": 4}); err != nil {
                panic(err)
            } else {
                c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
            }
        }
    })
    g.Run(":80")
}

Using buffer pooling, pre-parsing templates, and other such niceties are left as an exercise to any future readers.

If anyone knows of a better way to handle this without bypassing gin's parsing/rendering features, I'm very open to it.

  • 写回答

1条回答 默认 最新

  • doukang7486 2018-11-05 11:50
    关注

    you must be sure the Template render correctly,Because c.HTML will write directly to response, at this time some byte has been sent to client.

    you can use "html/template", and use buff to cache response data, instead of writing directly to response writer

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。