2016-09-16 142 views
0

我正在尝试为我的Kubernetes集群实现自定义默认http图像。我只得到了2个要求:在Golang中为Kubernetes自定义404错误页面

 Any image is permissable as long as: 
    1. It serves a 404 page at/
    2. It serves 200 on a /healthz endpoint 

截至目前,这是我得到的:

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, "Healthy as fuck") 
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 } 

它如预期,但我在这里的主要目的是显示所有的作品很酷的404错误页面,所以我需要使用Bootstrap,酷标签等等。但是这个代码总是在<pre></pre>标签内执行模板。

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

它毁掉了我想要做的一切。我该如何解决这个问题?

回答

1

基于此documentation for template,我想你可能想用“文本/模板”而不是“html/template”。

该网页说:

在HTML /模板上下文autoescaping生产安全,躲过了HTML输出

虽然:

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

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