dt2002 2016-09-16 16:51
浏览 65

Golang for Kubernetes中的自定义404错误页面

I am trying to implement a custom default-http image for my Kubernetes Cluster. I only got 2 requirements:

  • Any image is permissable as long as:

    1. It serves a 404 page at /
    2. It serves 200 on a /healthz endpoint

As of right now, that what I got:

  1 package main
  2
  3 import (
  4     "fmt"
  5     "net/http"
  6     "html/template"
  7 )
  8
  9 func main() {
 10     http.HandleFunc("/healthz", healhtzHandler)
 11     http.HandleFunc("/",errorHandler)
 12     http.ListenAndServe(":8000", nil)
 13 }
 14
 15 func healhtzHandler(w http.ResponseWriter, r *http.Request) {
 16     fmt.Fprint(w, "Really healthy")
 17 }
 18
 19 type Person struct {
 20     UserName string
 21 }
 22
 23 func errorHandler(w http.ResponseWriter, r *http.Request) {
 24     w.WriteHeader(404)
 25     t := template.New("fieldname example")
 26     t, _ = t.Parse("<h2>hello {{.UserName}}!</h2>")
 27     p := Person{UserName: "Astaxie"}
 28     t.Execute(w, p)
 29 }

It all works as expected, except that my main goal here is to display a cool 404 error page, so I will need to use Bootstrap, cool tags and etc. But this code always execute the template inside a <pre></pre> tag.

<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
&lt;h2&gt;hello Astaxie!&lt;/h2&gt;
</pre>
</body>
</html>

and it ruins everything I want to do. How do I solve this?

  • 写回答

1条回答 默认 最新

  • dongqin5604 2016-09-16 17:05
    关注

    Based on this documentation for template, I think you might want to use "text/template" instead of "html/template".

    That page says:

    The contextual autoescaping in html/template produces safe, escaped HTML output

    While:

    import "text/template"
    ...
    t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
    err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned') /script>")
    

    produces Hello, <script>alert('you have been pwned')</script>!

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看