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