Configure backend to serve assets over HTTP

This commit is contained in:
Rob Watson 2021-11-26 05:11:49 +01:00
parent bcb43e3517
commit 4c999cd5a2
3 changed files with 23 additions and 1 deletions

View File

@ -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=

View File

@ -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
}

View File

@ -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()
}