Custom 404 Error Page in Golang for Kubernetes

9/16/2016

I am trying to implement a custom default-http image for my Kubernetes Cluster. I only got 2 requirements:

  • Any image is permissable as long as:

    1. It serves a 404 page at /
    2. It serves 200 on a /healthz endpoint

As of right now, that what I got:

  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 }

It all works as expected, except that my main goal here is to display a cool 404 error page, so I will need to use Bootstrap, cool tags and etc. But this code always execute the template inside a <pre></pre> tag.

<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
<h2>hello Astaxie!</h2>
</pre>
</body>
</html>

and it ruins everything I want to do. How do I solve this?

-- CESCO
go
http
kubernetes

1 Answer

9/16/2016

Based on this documentation for template, I think you might want to use "text/template" instead of "html/template".

That page says:

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

While:

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

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

-- Himself12794
Source: StackOverflow