Skip to content

Commit

Permalink
Merge pull request #2246 from target/remove-dev-proxy
Browse files Browse the repository at this point in the history
dev: replace webpack-dev-server with watch
  • Loading branch information
mastercactapus authored Mar 17, 2022
2 parents d92a923 + 28b5642 commit 068b7d6
Show file tree
Hide file tree
Showing 16 changed files with 456 additions and 1,089 deletions.
4 changes: 2 additions & 2 deletions Procfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
build: while true; do make -qs bin/goalert || make bin/goalert || (echo '\033[0;31mBuild Failure'; sleep 3); sleep 0.1; done

@watch-file=./bin/goalert
goalert: ./bin/goalert -l=localhost:3030 --ui-url=http://localhost:3035 --db-url=postgres://goalert@localhost:5432/goalert?sslmode=disable --listen-sysapi=localhost:1234 --listen-prometheus=localhost:2112
goalert: ./bin/goalert -l=localhost:3030 --ui-dir=web/src/build --db-url=postgres://goalert@localhost:5432/goalert?sslmode=disable --listen-sysapi=localhost:1234 --listen-prometheus=localhost:2112

smtp: go run github.com/mailhog/MailHog -ui-bind-addr=localhost:8025 -api-bind-addr=localhost:8025 -smtp-bind-addr=localhost:1025 | grep -v KEEPALIVE
prom: bin/tools/prometheus --log.level=warn --config.file=devtools/prometheus/prometheus.yml --storage.tsdb.path=bin/prom-data/ --web.listen-address=localhost:9090

@watch-file=./web/src/webpack.config.js
ui: yarn workspace goalert-web webpack serve --config ./webpack.config.js
ui: yarn workspace goalert-web webpack --config ./webpack.config.js --watch
4 changes: 2 additions & 2 deletions Procfile.cypress
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
build: while true; do make -qs bin/goalert || make bin/goalert || (echo '\033[0;31mBuild Failure'; sleep 3); sleep 0.1; done

@watch-file=./bin/goalert
goalert: go run ./devtools/waitfor postgres://postgres@localhost:5433 && go run ./devtools/procwrap -test=localhost:3042 bin/goalert -l=localhost:3042 --ui-url=http://localhost:3045 --db-url=postgres://postgres@localhost:5433 --slack-base-url=http://localhost:3040/slack --log-errors-only
goalert: go run ./devtools/waitfor postgres://postgres@localhost:5433 && go run ./devtools/procwrap -test=localhost:3042 bin/goalert -l=localhost:3042 --ui-dir=web/src/build --db-url=postgres://postgres@localhost:5433 --slack-base-url=http://localhost:3040/slack --log-errors-only

@watch-file=./web/src/webpack.config.js
ui: yarn workspace goalert-web webpack serve --config ./webpack.config.js --port=3045
ui: yarn workspace goalert-web webpack --config ./webpack.config.js --watch

slack: go run ./devtools/mockslack/cmd/mockslack -client-id=000000000000.000000000000 -client-secret=00000000000000000000000000000000 -access-token=xoxp-000000000000-000000000000-000000000000-00000000000000000000000000000000 -prefix=/slack -single-user=bob -addr=localhost:3046

Expand Down
9 changes: 3 additions & 6 deletions app/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,6 @@ var (
Use: "version",
Short: "Output the current version.",
RunE: func(cmd *cobra.Command, args []string) error {

migrations := migrate.Names()

fmt.Printf(`Version: %s
Expand Down Expand Up @@ -472,7 +471,6 @@ Migration: %s (#%d)
up := viper.GetString("up")
if down != "" {
n, err := migrate.Down(ctx, c.DBURL, down)

if err != nil {
return errors.Wrap(err, "apply DOWN migrations")
}
Expand All @@ -483,7 +481,6 @@ Migration: %s (#%d)

if up != "" || down == "" {
n, err := migrate.Up(ctx, c.DBURL, up)

if err != nil {
return errors.Wrap(err, "apply UP migrations")
}
Expand All @@ -500,7 +497,6 @@ Migration: %s (#%d)
Use: "set-config",
Short: "Sets current config values in the DB from stdin.",
RunE: func(cmd *cobra.Command, args []string) error {

if viper.GetString("data-encryption-key") == "" && !viper.GetBool("allow-empty-data-encryption-key") {
return validation.NewFieldError("data-encryption-key", "Must not be empty, or set --allow-empty-data-encryption-key")
}
Expand Down Expand Up @@ -689,7 +685,7 @@ func getConfig(ctx context.Context) (Config, error) {

StubNotifiers: viper.GetBool("stub-notifiers"),

UIURL: viper.GetString("ui-url"),
UIDir: viper.GetString("ui-dir"),
}

if cfg.DBURL == "" {
Expand Down Expand Up @@ -773,7 +769,8 @@ func init() {
RootCmd.PersistentFlags().Bool("json", def.JSON, "Log in JSON format.")
RootCmd.PersistentFlags().Bool("log-errors-only", false, "Only log errors (superseeds other flags).")

RootCmd.Flags().String("ui-url", def.UIURL, "Proxy UI requests to an alternate host. Default is to serve bundled assets from memory.")
RootCmd.Flags().String("ui-dir", "", "Serve UI assets from a local directory instead of from memory.")

RootCmd.Flags().Bool("disable-https-redirect", def.DisableHTTPSRedirect, "Disable automatic HTTPS redirects.")

migrateCmd.Flags().String("up", "", "Target UP migration to apply.")
Expand Down
2 changes: 1 addition & 1 deletion app/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ type Config struct {

StubNotifiers bool

UIURL string
UIDir string

// InitialConfig will be pushed into the config store
// if specified before the engine is started.
Expand Down
3 changes: 1 addition & 2 deletions app/inithttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ func (app *App) initHTTP(ctx context.Context) error {
*app.twilioConfig,
)
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {

if strings.HasPrefix(req.URL.Path, "/api/v2/twilio/") {
twilioHandler.ServeHTTP(w, req)
return
Expand All @@ -270,7 +269,7 @@ func (app *App) initHTTP(ctx context.Context) error {
mux.HandleFunc("/health", app.healthCheck)
mux.HandleFunc("/health/engine", app.engineStatus)

webH, err := web.NewHandler(app.cfg.UIURL, app.cfg.HTTPPrefix)
webH, err := web.NewHandler(app.cfg.UIDir, app.cfg.HTTPPrefix)
if err != nil {
return err
}
Expand Down
11 changes: 6 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ require (
golang.org/x/crypto v0.0.0-20220213190939-1e6e3497d506
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8
golang.org/x/sys v0.0.0-20220209214540-3681064d5158
golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
golang.org/x/tools v0.1.9
golang.org/x/tools v0.1.10
google.golang.org/genproto v0.0.0-20220211171837-173942840c17 // indirect
google.golang.org/grpc v1.44.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0
Expand All @@ -79,7 +79,7 @@ require (
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect
gopkg.in/square/go-jose.v2 v2.5.1 // indirect
honnef.co/go/tools v0.2.2
honnef.co/go/tools v0.3.0-0.dev.0.20220306074811-23e1086441d2
)

require (
Expand All @@ -95,7 +95,7 @@ require (
cloud.google.com/go/monitoring v1.1.0 // indirect
cloud.google.com/go/storage v1.18.2 // indirect
cloud.google.com/go/trace v1.0.0 // indirect
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/BurntSushi/toml v1.0.0 // indirect
github.com/Masterminds/goutils v1.1.0 // indirect
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Masterminds/sprig v2.22.0+incompatible // indirect
Expand Down Expand Up @@ -154,7 +154,8 @@ require (
github.com/uber/jaeger-client-go v2.25.0+incompatible // indirect
github.com/vanng822/css v0.0.0-20190504095207-a21e860bcd04 // indirect
github.com/vanng822/go-premailer v0.0.0-20191214114701-be27abe028fe // indirect
golang.org/x/mod v0.5.1 // indirect
golang.org/x/exp/typeparams v0.0.0-20220314205449-43aec2f8a4e7 // indirect
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
Expand Down
24 changes: 16 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ contrib.go.opencensus.io/exporter/stackdriver v0.13.10/go.mod h1:I5htMbyta491eUx
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/99designs/gqlgen v0.16.0 h1:7Qc4Ll3mfN3doAyUWOgtGLcBGu+KDgK48HdkBGLZVFs=
github.com/99designs/gqlgen v0.16.0/go.mod h1:nbeSjFkqphIqpZsYe1ULVz0yfH8hjpJdJIQoX/e0G2I=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU=
github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/Masterminds/goutils v1.1.0 h1:zukEsf/1JZwCMgHiK3GZftabmxiCw4apj3a28RPBiVg=
Expand Down Expand Up @@ -791,7 +793,11 @@ golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20220314205449-43aec2f8a4e7 h1:mzVEuUhnztMdHb426A1o6cjz5ha6YV3t6zFTBXqSon4=
golang.org/x/exp/typeparams v0.0.0-20220314205449-43aec2f8a4e7/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand All @@ -818,8 +824,9 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
Expand Down Expand Up @@ -986,8 +993,8 @@ golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86 h1:A9i04dxx7Cribqbs8jf3FQLogkL/CV2YN7hj9KWJCkc=
golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
Expand Down Expand Up @@ -1071,8 +1078,9 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8=
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down Expand Up @@ -1289,8 +1297,8 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
honnef.co/go/tools v0.2.2 h1:MNh1AVMyVX23VUHE2O27jm6lNj3vjO5DexS4A1xvnzk=
honnef.co/go/tools v0.2.2/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY=
honnef.co/go/tools v0.3.0-0.dev.0.20220306074811-23e1086441d2 h1:utiSabORbG/JeX7MlmKMdmsjwom2+v8zmdb6SoBe4UY=
honnef.co/go/tools v0.3.0-0.dev.0.20220306074811-23e1086441d2/go.mod h1:dZI0HmIvwDMW8owtLBJxTHoeX48yuF5p5pDy3y73jGU=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
63 changes: 63 additions & 0 deletions web/etaghandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package web

import (
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"sync"
)

type etagHandler struct {
tags map[string]string
h http.Handler
fs http.FileSystem
mx sync.Mutex
static bool
}

func NewEtagFileServer(files http.FileSystem, static bool) http.Handler {
return &etagHandler{
tags: make(map[string]string),
h: http.FileServer(files),
fs: files,
static: static,
}
}

func (e *etagHandler) etag(name string) string {
e.mx.Lock()
defer e.mx.Unlock()

if tag, ok := e.tags[name]; e.static && ok {
return tag
}

f, err := e.fs.Open(name)
if err != nil {
e.tags[name] = ""
return ""
}
defer f.Close()

h := sha256.New()

_, err = io.Copy(h, f)
if err != nil {
e.tags[name] = ""
return ""
}

tag := `W/"` + hex.EncodeToString(h.Sum(nil)) + `"`
e.tags[name] = tag
return tag
}

func (e *etagHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if tag := e.etag(req.URL.Path); tag != "" {
w.Header().Set("Cache-Control", "public; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
w.Header().Set("ETag", tag)
}

e.h.ServeHTTP(w, req)
}
75 changes: 25 additions & 50 deletions web/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,67 +6,36 @@ import (
"embed"
"encoding/hex"
"fmt"
"github.com/target/goalert/config"
"github.com/target/goalert/util/errutil"
"html/template"
"io/fs"
"net/http"
"net/http/httputil"
"net/url"
"path"
"sync"
"time"

"github.com/pkg/errors"
"github.com/target/goalert/config"
"github.com/target/goalert/util/errutil"
)

//go:embed src/build
var bundleFS embed.FS

//go:embed live.js
var liveJS string

// NewHandler creates a new http.Handler that will serve UI files
// using bundled assets or by proxying to urlStr if set.
func NewHandler(urlStr, prefix string) (http.Handler, error) {
// using bundled assets or locally if uiDir if set.
func NewHandler(uiDir, prefix string) (http.Handler, error) {
mux := http.NewServeMux()

etags := make(map[string]string)
var mx sync.Mutex
calcTag := func(name string, data []byte) string {
mx.Lock()
defer mx.Unlock()
tag, ok := etags[name]
if ok {
return tag
}
sum := sha256.Sum256(data)
tag = `W/"` + hex.EncodeToString(sum[:]) + `"`
etags[name] = tag
return tag
}

var extraScripts []string
if urlStr == "" {
mux.HandleFunc("/static/", func(w http.ResponseWriter, req *http.Request) {
data, err := bundleFS.ReadFile(path.Join("src/build", req.URL.Path))
if errors.Is(err, fs.ErrNotExist) {
http.NotFound(w, req)
return
}

w.Header().Set("Cache-Control", "public; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
w.Header().Set("ETag", calcTag(req.URL.Path, data))

http.ServeContent(w, req, req.URL.Path, time.Time{}, bytes.NewReader(data))
})
var extraJS string
if uiDir != "" {
extraJS = liveJS
mux.Handle("/static/", NoCache(NewEtagFileServer(http.Dir(uiDir), false)))
} else {
u, err := url.Parse(urlStr)
sub, err := fs.Sub(bundleFS, "src/build")
if err != nil {
return nil, errors.Wrap(err, "parse url")
return nil, err
}
proxy := httputil.NewSingleHostReverseProxy(u)
mux.Handle("/static/", proxy)
mux.Handle("/build/", proxy)

// dev mode
extraScripts = []string{"vendor.js"}
mux.Handle("/static/", NewEtagFileServer(http.FS(sub), true))
}

mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
Expand All @@ -76,17 +45,23 @@ func NewHandler(urlStr, prefix string) (http.Handler, error) {
err := indexTmpl.Execute(&buf, renderData{
ApplicationName: cfg.ApplicationName(),
Prefix: prefix,
ExtraScripts: extraScripts,
ExtraJS: template.JS(extraJS),
})
if errutil.HTTPError(req.Context(), w, err) {
return
}

h := sha256.New()
h.Write(buf.Bytes())
indexETag := fmt.Sprintf(`"sha256-%s"`, hex.EncodeToString(h.Sum(nil)))

w.Header().Set("Cache-Control", "private; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
indexETag := fmt.Sprintf(`W/"sha256-%s"`, hex.EncodeToString(h.Sum(nil)))
w.Header().Set("ETag", indexETag)

if uiDir == "" {
w.Header().Set("Cache-Control", "private; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
} else {
w.Header().Set("Cache-Control", "no-store")
}

http.ServeContent(w, req, "/", time.Time{}, bytes.NewReader(buf.Bytes()))
})

Expand Down
Loading

0 comments on commit 068b7d6

Please sign in to comment.