diff --git a/backend/.env.example b/backend/.env.example index 752a9f9..c60e03e 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -6,3 +6,6 @@ AWS_REGION= S3_BUCKET= DATABASE_URL= + +# If set, files in this location will be served over HTTP at /. +ASSETS_HTTP_BASE_PATH= diff --git a/backend/config/config.go b/backend/config/config.go index 5684fa4..4918cfe 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -20,6 +20,7 @@ type Config struct { AWSSecretAccessKey string AWSRegion string S3Bucket string + AssetsHTTPBasePath string } func NewFromEnv() (Config, error) { @@ -61,6 +62,8 @@ func NewFromEnv() (Config, error) { return Config{}, errors.New("S3_BUCKET not set") } + assetsHTTPBasePath := os.Getenv("ASSETS_HTTP_BASE_PATH") + return Config{ Environment: env, DatabaseURL: databaseURL, @@ -68,5 +71,6 @@ func NewFromEnv() (Config, error) { AWSSecretAccessKey: awsSecretAccessKey, AWSRegion: awsRegion, S3Bucket: s3Bucket, + AssetsHTTPBasePath: assetsHTTPBasePath, }, nil } diff --git a/backend/server/server.go b/backend/server/server.go index b9cea9c..3c49350 100644 --- a/backend/server/server.go +++ b/backend/server/server.go @@ -247,13 +247,28 @@ func Start(options Options) error { // TODO: configure CORS grpcWebServer := grpcweb.WrapServer(grpcServer, grpcweb.WithOriginFunc(func(string) bool { return true })) + log := logger.Sugar() + fileHandler := http.NotFoundHandler() + if options.Config.AssetsHTTPBasePath != "" { + log.With("basePath", options.Config.AssetsHTTPBasePath).Info("Configured to serve assets over HTTP") + fileHandler = http.FileServer(http.Dir(options.Config.AssetsHTTPBasePath)) + } + httpServer := http.Server{ Addr: options.BindAddr, ReadTimeout: options.Timeout, WriteTimeout: options.Timeout, - Handler: http.HandlerFunc(grpcWebServer.ServeHTTP), + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !grpcWebServer.IsGrpcWebRequest(r) && !grpcWebServer.IsAcceptableGrpcCorsRequest(r) { + fileHandler.ServeHTTP(w, r) + return + } + grpcWebServer.ServeHTTP(w, r) + }), } + log.Infof("Listening at %s", options.BindAddr) + return httpServer.ListenAndServe() }