4
0

singleFrontend.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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("/oauth/login", handleOAuthLogin)
  46. mux.HandleFunc("/oauth/callback", handleOAuthCallback)
  47. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  48. logDebugRequest(cfg, "ui ", r)
  49. webuiProxy.ServeHTTP(w, r)
  50. })
  51. if cfg.Prometheus.Enabled {
  52. promURL, _ := url.Parse("http://" + cfg.ListenAddressPrometheus)
  53. promProxy := httputil.NewSingleHostReverseProxy(promURL)
  54. mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
  55. logDebugRequest(cfg, "prom", r)
  56. promProxy.ServeHTTP(w, r)
  57. })
  58. }
  59. oauth2Init(cfg)
  60. srv := &http.Server{
  61. Addr: cfg.ListenAddressSingleHTTPFrontend,
  62. Handler: mux,
  63. }
  64. log.Fatal(srv.ListenAndServe())
  65. }