Przeglądaj źródła

add static file serving to backend

Alexander Belanger 4 lat temu
rodzic
commit
bc7fc86986
1 zmienionych plików z 22 dodań i 0 usunięć
  1. 22 0
      api/server/router/router.go

+ 22 - 0
api/server/router/router.go

@@ -2,6 +2,9 @@ package router
 
 import (
 	"net/http"
+	"os"
+	"path"
+	"strings"
 
 	"github.com/go-chi/chi"
 	"github.com/porter-dev/porter/api/server/authn"
@@ -90,6 +93,25 @@ func NewAPIRouter(config *config.Config) *chi.Mux {
 		registerRoutes(config, allRoutes)
 	})
 
+	staticFilePath := config.ServerConf.StaticFilePath
+	fs := http.FileServer(http.Dir(staticFilePath))
+
+	r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
+		if _, err := os.Stat(staticFilePath + r.RequestURI); os.IsNotExist(err) {
+			w.Header().Set("Cache-Control", "no-cache")
+
+			http.StripPrefix(r.URL.Path, fs).ServeHTTP(w, r)
+		} else {
+			// Set static files involving html, js, or empty cache to "no-cache", which means they must be validated
+			// for changes before the browser uses the cache
+			if base := path.Base(r.URL.Path); strings.Contains(base, "html") || strings.Contains(base, "js") || base == "." || base == "/" {
+				w.Header().Set("Cache-Control", "no-cache")
+			}
+
+			fs.ServeHTTP(w, r)
+		}
+	})
+
 	return r
 }