Skip to content

Commit e1bb745

Browse files
committed
perf: gzip and cache static files
1 parent 7d61a21 commit e1bb745

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

gzip.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package shushtar
2+
3+
import (
4+
"compress/gzip"
5+
"io"
6+
"net/http"
7+
"strings"
8+
)
9+
10+
type gzipResponseWriter struct {
11+
io.Writer
12+
http.ResponseWriter
13+
}
14+
15+
// Use the Writer part of gzipResponseWriter to write the output.
16+
17+
func (w gzipResponseWriter) Write(b []byte) (int, error) {
18+
return w.Writer.Write(b)
19+
}
20+
21+
func makeGzipHandler(handler http.HandlerFunc) http.HandlerFunc {
22+
return func(resp http.ResponseWriter, req *http.Request) {
23+
// Check if the client can accept the gzip encoding.
24+
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
25+
// The client cannot accept it, so return the output
26+
// uncompressed.
27+
handler(resp, req)
28+
return
29+
}
30+
// Set the HTTP header indicating encoding.
31+
resp.Header().Set("Content-Encoding", "gzip")
32+
gzipWriter := gzip.NewWriter(resp)
33+
defer gzipWriter.Close()
34+
handler(gzipResponseWriter{Writer: gzipWriter, ResponseWriter: resp}, req)
35+
}
36+
}

shushtar.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ import (
66
"encoding/base64"
77
"errors"
88
"fmt"
9-
"github.com/lightningnetwork/lnd/lncfg"
109
"io/ioutil"
1110
"net"
1211
"net/http"
1312
"os"
1413
"path/filepath"
14+
"regexp"
1515
"strings"
1616
"sync"
1717
"time"
@@ -24,6 +24,7 @@ import (
2424
"github.com/lightninglabs/loop/loopd"
2525
"github.com/lightninglabs/loop/looprpc"
2626
"github.com/lightningnetwork/lnd"
27+
"github.com/lightningnetwork/lnd/lncfg"
2728
"github.com/lightningnetwork/lnd/lnrpc"
2829
"github.com/lightningnetwork/lnd/lntest/wait"
2930
"github.com/lightningnetwork/lnd/macaroons"
@@ -460,7 +461,16 @@ func (g *Shushtar) startGrpcWebProxy() error {
460461
// something we don't know in which case the static file server
461462
// will answer with a 404.
462463
log.Infof("Handling static file request: %s", req.URL.Path)
463-
staticFileServer.ServeHTTP(resp, req)
464+
// add 1-year cache header for static files. React uses content-based
465+
// hashes in file names, so when any file is updated, the url will
466+
// change causing the browser cached version to be invalidated
467+
var re = regexp.MustCompile(`^\/(static|fonts|icons)\/.*`)
468+
if re.MatchString(req.URL.Path) {
469+
resp.Header().Set("Cache-Control", "max-age=31536000")
470+
}
471+
// transfer static files using gzip to save up to 70% of bandwidth
472+
gzipHandler := makeGzipHandler(staticFileServer.ServeHTTP)
473+
gzipHandler(resp, req)
464474
}
465475

466476
// Create and start our HTTPS server now that will handle both gRPC web

0 commit comments

Comments
 (0)