Skip to content

Commit 572eb25

Browse files
committed
Add support for custom error pages
1 parent b901486 commit 572eb25

File tree

2 files changed

+29
-13
lines changed

2 files changed

+29
-13
lines changed

errors.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,24 @@
44

55
package tunnel
66

7-
import "errors"
7+
import (
8+
"errors"
9+
"io/ioutil"
10+
)
811

912
var (
10-
errClientNotSubscribed = errors.New("client not subscribed")
11-
errClientNotConnected = errors.New("client not connected")
12-
errClientAlreadyConnected = errors.New("client already connected")
13+
errClientNotSubscribed = newError("clientNotSubscribed.html", "client not subscribed")
14+
errClientNotConnected = newError("clientNotConnected.html", "client not connected")
15+
errClientAlreadyConnected = newError("clientAlreadyConnected.html", "client already connected")
1316

14-
errUnauthorised = errors.New("unauthorised")
17+
errUnauthorised = newError("unauthorised.html", "unauthorised")
1518
)
19+
20+
func newError(fileName string, defaultMsg string) error {
21+
content, err := ioutil.ReadFile("html/errors/" + fileName)
22+
if err != nil {
23+
// handle the case where the file doesn't exist
24+
return errors.New(defaultMsg)
25+
}
26+
return errors.New(string(content))
27+
}

server.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -564,22 +564,26 @@ func (s *Server) listen(l net.Listener, identifier id.ID) {
564564
// ServeHTTP proxies http connection to the client.
565565
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
566566
resp, err := s.RoundTrip(r)
567-
if err == errUnauthorised {
568-
w.Header().Set("WWW-Authenticate", "Basic realm=\"User Visible Realm\"")
569-
http.Error(w, err.Error(), http.StatusUnauthorized)
570-
return
571-
}
572567
if err != nil {
568+
code := http.StatusBadGateway
569+
if err == errUnauthorised {
570+
w.Header().Set("WWW-Authenticate", "Basic realm=\"User Visible Realm\"")
571+
code = http.StatusUnauthorized
572+
} else if err == errClientNotSubscribed {
573+
code = http.StatusNotFound
574+
}
573575
s.logger.Log(
574576
"level", 0,
575577
"action", "round trip failed",
576578
"addr", r.RemoteAddr,
577579
"host", r.Host,
578580
"url", r.URL,
579-
"err", err,
581+
"code", code,
580582
)
581-
582-
http.Error(w, err.Error(), http.StatusBadGateway)
583+
w.Header().Set("Content-Type", "text/html; charset=utf-8")
584+
w.Header().Set("X-Content-Type-Options", "nosniff")
585+
w.WriteHeader(code)
586+
fmt.Fprintln(w, err.Error())
583587
return
584588
}
585589
defer resp.Body.Close()

0 commit comments

Comments
 (0)