singleFrontend.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. if cfg.Prometheus.Enabled {
  50. promURL, _ := url.Parse("http://" + cfg.ListenAddressPrometheus)
  51. promProxy := httputil.NewSingleHostReverseProxy(promURL)
  52. mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
  53. log.Debugf("prom req: %q", r.URL)
  54. promProxy.ServeHTTP(w, r)
  55. })
  56. }
  57. srv := &http.Server{
  58. Addr: cfg.ListenAddressSingleHTTPFrontend,
  59. Handler: mux,
  60. }
  61. log.Fatal(srv.ListenAndServe())
  62. }