2016-09-16 136 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>!