Add redirection middleware

This commit is contained in:
Audrius Butkevicius 2014-09-12 20:28:47 +01:00
parent 583bcfb3c7
commit 3662decb8b
1 changed files with 38 additions and 24 deletions

View File

@ -58,30 +58,25 @@ func init() {
func startGUI(cfg config.GUIConfiguration, assetDir string, m *model.Model) error { func startGUI(cfg config.GUIConfiguration, assetDir string, m *model.Model) error {
var listener net.Listener var listener net.Listener
var err error var err error
if cfg.UseTLS {
cert, err := loadCert(confDir, "https-") cert, err := loadCert(confDir, "https-")
if err != nil { if err != nil {
l.Infoln("Loading HTTPS certificate:", err) l.Infoln("Loading HTTPS certificate:", err)
l.Infoln("Creating new HTTPS certificate") l.Infoln("Creating new HTTPS certificate")
newCertificate(confDir, "https-") newCertificate(confDir, "https-")
cert, err = loadCert(confDir, "https-") cert, err = loadCert(confDir, "https-")
} }
if err != nil { if err != nil {
return err return err
} }
tlsCfg := &tls.Config{ tlsCfg := &tls.Config{
Certificates: []tls.Certificate{cert}, Certificates: []tls.Certificate{cert},
ServerName: "syncthing", ServerName: "syncthing",
} }
listener, err = tls.Listen("tcp", cfg.Address, tlsCfg)
if err != nil { listener, err = NewDowngradingListener(cfg.Address, tlsCfg)
return err if err != nil {
} return err
} else {
listener, err = net.Listen("tcp", cfg.Address)
if err != nil {
return err
}
} }
// The GET handlers // The GET handlers
@ -144,6 +139,9 @@ func startGUI(cfg config.GUIConfiguration, assetDir string, m *model.Model) erro
handler = basicAuthAndSessionMiddleware(cfg, handler) handler = basicAuthAndSessionMiddleware(cfg, handler)
} }
// Add our redirection middleware
handler = redirectionMiddleware(handler, cfg.Address, cfg.UseTLS)
go http.Serve(listener, handler) go http.Serve(listener, handler)
return nil return nil
} }
@ -161,6 +159,22 @@ func getPostHandler(get, post http.Handler) http.Handler {
}) })
} }
func redirectionMiddleware(h http.Handler, host string, usingTLS bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS == nil && usingTLS {
r.URL.Host = host
r.URL.Scheme = "https"
http.Redirect(w, r, r.URL.String(), http.StatusFound)
} else if r.TLS != nil && !usingTLS {
r.URL.Host = host
r.URL.Scheme = "http"
http.Redirect(w, r, r.URL.String(), http.StatusFound)
} else {
h.ServeHTTP(w, r)
}
})
}
func noCacheMiddleware(h http.Handler) http.Handler { func noCacheMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Cache-Control", "no-cache")