From 930d16a1a2d9a7e8f233ed2e7a6975a3676db87e Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Sat, 30 Sep 2017 11:04:33 -0700 Subject: [PATCH] tun2: return a snazzy html page when no backend is connected --- lib/tun2/server.go | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/tun2/server.go b/lib/tun2/server.go index 12253c0..9b2fb80 100644 --- a/lib/tun2/server.go +++ b/lib/tun2/server.go @@ -1,13 +1,17 @@ package tun2 import ( + "bytes" "context" "crypto/tls" "encoding/json" "errors" + "fmt" + "io/ioutil" "math/rand" "net" "net/http" + "os" "sync" "time" @@ -444,7 +448,36 @@ func (s *Server) RoundTrip(req *http.Request) (*http.Response, error) { "uri": req.RequestURI, }) - return nil, ErrNoSuchBackend + template := `no backends connected

no backends connected

Please ensure a backend is running for ${HOST}. This is request ID ${REQ_ID}.

` + + resbody := []byte(os.Expand(template, func(in string) string { + switch in { + case "HOST": + return req.Host + case "REQ_ID": + return req.Header.Get("X-Request-Id") + } + + return "" + })) + reshdr := req.Header + reshdr.Set("Content-Type", "text/html; charset=utf-8") + + resp := &http.Response{ + Status: fmt.Sprintf("%d Bad Gateway", http.StatusBadGateway), + StatusCode: http.StatusBadGateway, + Body: ioutil.NopCloser(bytes.NewBuffer(resbody)), + + Proto: req.Proto, + ProtoMajor: req.ProtoMajor, + ProtoMinor: req.ProtoMinor, + Header: reshdr, + ContentLength: len(resbody), + Close: true, + Request: req, + } + + return resp, nil } }