gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:14:48 24 4
gpt4 key购买 nike

我正在尝试为我的 Kubernetes 集群实现一个自定义的 default-http 图像。我只有 2 个要求:

  • 任何图片都可以,只要:

    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>

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

最佳答案

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

那个页面说:

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

同时:

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

关于http - Golang for Kubernetes 中的自定义 404 错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com