Skip to content

Commit 03cf2a0

Browse files
committed
bundle-server: serve with 'ServeContent()'
Use 'OpenFile()' + 'ServeContent()', rather than 'ReadFile()' + 'Write()' to serve bundle and bundle list content. There are a few (fairly minor) benefits to 'ServeContent()': it does not buffer the full file contents before writing to the response writer, and it automatically derives the 'Content-Type' and other headers from the file content. Signed-off-by: Victoria Dye <[email protected]>
1 parent aef1250 commit 03cf2a0

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

cmd/git-bundle-web-server/bundle-server.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ import (
66
"net/http"
77
"os"
88
"os/signal"
9+
"path/filepath"
910
"strings"
1011
"sync"
1112
"syscall"
13+
"time"
1214

1315
"github.com/github/git-bundle-server/internal/common"
1416
"github.com/github/git-bundle-server/internal/core"
@@ -70,7 +72,7 @@ func (b *bundleWebServer) serve(w http.ResponseWriter, r *http.Request) {
7072
defer exitRegion()
7173

7274
path := r.URL.Path
73-
owner, repo, file, err := b.parseRoute(ctx, path)
75+
owner, repo, filename, err := b.parseRoute(ctx, path)
7476
if err != nil {
7577
w.WriteHeader(http.StatusNotFound)
7678
fmt.Printf("Failed to parse route: %s\n", err)
@@ -97,20 +99,22 @@ func (b *bundleWebServer) serve(w http.ResponseWriter, r *http.Request) {
9799
return
98100
}
99101

100-
if file == "" {
101-
file = "bundle-list"
102+
var fileToServe string
103+
if filename == "" {
104+
fileToServe = filepath.Join(repository.WebDir, "bundle-list")
105+
} else {
106+
fileToServe = filepath.Join(repository.WebDir, filename)
102107
}
103108

104-
fileToServe := repository.WebDir + "/" + file
105-
data, err := os.ReadFile(fileToServe)
109+
file, err := os.OpenFile(fileToServe, os.O_RDONLY, 0)
106110
if err != nil {
107111
w.WriteHeader(http.StatusNotFound)
108-
fmt.Printf("Failed to read file\n")
112+
fmt.Printf("Failed to open file\n")
109113
return
110114
}
111115

112-
fmt.Printf("Successfully serving content for %s/%s\n", route, file)
113-
w.Write(data)
116+
fmt.Printf("Successfully serving content for %s/%s\n", route, filename)
117+
http.ServeContent(w, r, filename, time.UnixMicro(0), file)
114118
}
115119

116120
func (b *bundleWebServer) StartServerAsync(ctx context.Context) {

0 commit comments

Comments
 (0)