Add ability to enable static file serving

This commit is contained in:
Denis Arh
2020-03-27 22:26:22 +01:00
parent 2f631f055a
commit b48010730b
4 changed files with 112 additions and 12 deletions
+17 -1
View File
@@ -20,6 +20,14 @@ type (
MetricsPassword string `env:"HTTP_METRICS_PASSWORD"`
EnablePanicReporting bool `env:"HTTP_REPORT_PANIC"`
ApiEnabled bool `env:"HTTP_API_ENABLED"`
ApiBaseUrl string `env:"HTTP_API_BASE_URL"`
WebappEnabled bool `env:"HTTP_WEBAPP_ENABLED"`
WebappBaseUrl string `env:"HTTP_WEBAPP_BASE_URL"`
WebappBaseDir string `env:"HTTP_WEBAPP_BASE_DIR"`
WebappList string `env:"HTTP_WEBAPP_LIST"`
}
)
@@ -35,11 +43,19 @@ func HTTP(pfix string) (o *HTTPServerOpt) {
MetricsServiceLabel: "corteza",
MetricsUsername: "metrics",
// Reports panics to Sentry throught HTTP middleware
// Reports panics to Sentry through HTTP middleware
EnablePanicReporting: true,
// Setting metrics password to random string to prevent security accidents...
MetricsPassword: string(rand.Bytes(5)),
ApiEnabled: true,
ApiBaseUrl: "",
WebappEnabled: false,
WebappBaseUrl: "/",
WebappBaseDir: "/webapp",
WebappList: "admin,auth,messaging,compose",
}
fill(o, pfix)
+1
View File
@@ -235,6 +235,7 @@ func (r *runner) serve(ctx context.Context) (err error) {
if err = r.Provision(ctx); err != nil {
return
}
r.setupHttpApi()
r.setupGRPCServices()
+51
View File
@@ -0,0 +1,51 @@
package webapp
import (
"fmt"
"github.com/cortezaproject/corteza-server/pkg/app/options"
"github.com/go-chi/chi"
"net/http"
"os"
"path"
"strings"
)
func MakeWebappServer(opt options.HTTPServerOpt) func(r chi.Router) {
// Serves static files directly from FS
return func(r chi.Router) {
fileserver := http.FileServer(http.Dir(opt.WebappBaseDir))
for _, app := range strings.Split(opt.WebappList, ",") {
basedir := path.Join(opt.WebappBaseUrl, app)
serveConfig(r, basedir, opt.ApiBaseUrl)
r.Get(basedir+"*", serveIndex(opt.WebappBaseDir, basedir+"/index.html", fileserver))
}
serveConfig(r, opt.WebappBaseUrl, opt.ApiBaseUrl)
r.Get(opt.WebappBaseUrl+"*", serveIndex(opt.WebappBaseDir, opt.WebappBaseUrl+"/index.html", fileserver))
}
}
// Serves index.html in case the requested file isn't found (or some other os.Stat error)
func serveIndex(assetPath string, indexPath string, serve http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
indexPage := path.Join(assetPath, indexPath)
requestedPage := path.Join(assetPath, r.URL.Path)
_, err := os.Stat(requestedPage)
if err != nil {
http.ServeFile(w, r, indexPage)
return
}
serve.ServeHTTP(w, r)
}
}
func serveConfig(r chi.Router, appUrl, apiBaseUrl string) {
r.Get(strings.TrimRight(appUrl, "/")+"/config.js", func(w http.ResponseWriter, r *http.Request) {
const line = "window.%sAPI = '%s/%s';\n"
_, _ = fmt.Fprintf(w, line, "System", apiBaseUrl, "system")
_, _ = fmt.Fprintf(w, line, "Messaging", apiBaseUrl, "messaging")
_, _ = fmt.Fprintf(w, line, "Compose", apiBaseUrl, "compose")
})
}