singleFrontend.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package httpservers
  2. /*
  3. This file implements a very simple, lightweight reverse proxy so that REST and
  4. the webui can be accessed from a single endpoint.
  5. This makes external reverse proxies (treafik, haproxy, etc) easier, CORS goes
  6. away, and several other issues.
  7. */
  8. import (
  9. config "github.com/OliveTin/OliveTin/internal/config"
  10. log "github.com/sirupsen/logrus"
  11. "net/http"
  12. "net/http/httputil"
  13. "net/url"
  14. "strings"
  15. )
  16. // StartSingleHTTPFrontend will create a reverse proxy that proxies the API
  17. // and webui internally.
  18. func StartSingleHTTPFrontend(cfg *config.Config) {
  19. log.WithFields(log.Fields{
  20. "address": cfg.ListenAddressSingleHTTPFrontend,
  21. }).Info("Starting single HTTP frontend")
  22. apiURL, _ := url.Parse("http://" + cfg.ListenAddressRestActions)
  23. apiProxy := httputil.NewSingleHostReverseProxy(apiURL)
  24. webuiURL, _ := url.Parse("http://" + cfg.ListenAddressWebUI)
  25. webuiProxy := httputil.NewSingleHostReverseProxy(webuiURL)
  26. mux := http.NewServeMux()
  27. mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
  28. log.Debugf("api req: %q", r.URL)
  29. apiProxy.ServeHTTP(w, r)
  30. })
  31. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  32. if strings.Contains(r.Header.Get("Connection"), "Upgrade") {
  33. handleWebsocket(w, r)
  34. } else {
  35. log.Debugf("ui req: %q", r.URL)
  36. webuiProxy.ServeHTTP(w, r)
  37. }
  38. })
  39. srv := &http.Server{
  40. Addr: cfg.ListenAddressSingleHTTPFrontend,
  41. Handler: mux,
  42. }
  43. log.Fatal(srv.ListenAndServe())
  44. }