簡體   English   中英

Golang for Kubernetes中的自定義404錯誤頁面

[英]Custom 404 Error Page in Golang for Kubernetes

我正在嘗試為我的Kubernetes集群實現自定義的default-http映像。 我只有兩個要求:

  • 只要允許以下任何圖像:

    1. 它在/提供404頁面
    2. 它在/ healthz終結點上服務200

截至目前,我得到的是:

  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 }

一切都按預期工作,除了我的主要目標是顯示一個很酷的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>

它毀了我想做的一切。 我該如何解決?

基於此template的文檔 ,我認為您可能想使用“ text / template”而不是“ html / template”。

該頁面顯示:

html / template中的上下文自動轉義產生安全的,轉義的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>!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM