4
0

singleFrontend.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "github.com/OliveTin/OliveTin/internal/websocket"
  11. log "github.com/sirupsen/logrus"
  12. "net/http"
  13. "net/http/httputil"
  14. "net/url"
  15. )
  16. func logDebugRequest(cfg *config.Config, source string, r *http.Request) {
  17. if cfg.LogDebugOptions.SingleFrontendRequests {
  18. log.Debugf("SingleFrontend HTTP Req URL %v: %q", source, r.URL)
  19. if cfg.LogDebugOptions.SingleFrontendRequestHeaders {
  20. for name, values := range r.Header {
  21. log.Debugf("SingleFrontend HTTP Req Hdr: %v = %v", name, values)
  22. }
  23. }
  24. }
  25. }
  26. // StartSingleHTTPFrontend will create a reverse proxy that proxies the API
  27. // and webui internally.
  28. func StartSingleHTTPFrontend(cfg *config.Config) {
  29. log.WithFields(log.Fields{
  30. "address": cfg.ListenAddressSingleHTTPFrontend,
  31. }).Info("Starting single HTTP frontend")
  32. apiURL, _ := url.Parse("http://" + cfg.ListenAddressRestActions)
  33. apiProxy := httputil.NewSingleHostReverseProxy(apiURL)
  34. webuiURL, _ := url.Parse("http://" + cfg.ListenAddressWebUI)
  35. webuiProxy := httputil.NewSingleHostReverseProxy(webuiURL)
  36. mux := http.NewServeMux()
  37. mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
  38. logDebugRequest(cfg, "api ", r)
  39. apiProxy.ServeHTTP(w, r)
  40. })
  41. mux.HandleFunc("/websocket", func(w http.ResponseWriter, r *http.Request) {
  42. logDebugRequest(cfg, "ws ", r)
  43. websocket.HandleWebsocket(w, r)
  44. })
  45. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  46. logDebugRequest(cfg, "ui ", r)
  47. webuiProxy.ServeHTTP(w, r)
  48. })
  49. srv := &http.Server{
  50. Addr: cfg.ListenAddressSingleHTTPFrontend,
  51. Handler: mux,
  52. }
  53. log.Fatal(srv.ListenAndServe())
  54. }