tun2: return a snazzy html page when no backend is connected

This commit is contained in:
Cadey Ratio 2017-09-30 11:04:33 -07:00
parent 235eed3d84
commit 930d16a1a2
No known key found for this signature in database
GPG Key ID: D607EE27C2E7F89A
1 changed files with 34 additions and 1 deletions

View File

@ -1,13 +1,17 @@
package tun2 package tun2
import ( import (
"bytes"
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"io/ioutil"
"math/rand" "math/rand"
"net" "net"
"net/http" "net/http"
"os"
"sync" "sync"
"time" "time"
@ -444,7 +448,36 @@ func (s *Server) RoundTrip(req *http.Request) (*http.Response, error) {
"uri": req.RequestURI, "uri": req.RequestURI,
}) })
return nil, ErrNoSuchBackend template := `<html><head><title>no backends connected</title></head><body><h1>no backends connected</h1><p>Please ensure a backend is running for ${HOST}. This is request ID ${REQ_ID}.</p></body></html>`
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 "<unknown>"
}))
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
} }
} }