Skip to content

Commit

Permalink
Log the exact size sent over the wire in host and open an API for it
Browse files Browse the repository at this point in the history
Previously we were logging the full file size not just the parts of the
file actually sent. This size also includes headers and generated pages
like the directory listing.
  • Loading branch information
fsmv committed Jul 5, 2024
1 parent 702ff35 commit 5aab2c4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
7 changes: 5 additions & 2 deletions host/embedhost/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,14 @@ func Run(flags *flag.FlagSet, args []string) {
return // Auth failed!
}
if *logRequests {
size, _ := dir.FileSize(req.URL.Path)
w = tools.NewSizeTrackerHTTPResponseWriter(w)
}
fileServer.ServeHTTP(w, req)
if *logRequests {
size := w.(tools.SizeTrackerHTTPResponseWriter).BytesRead()
log.Printf("%v requested and was served %v (%v bytes)",
clientName, fullPath, size)
}
fileServer.ServeHTTP(w, req)
},
)))

Expand Down
29 changes: 29 additions & 0 deletions tools/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -516,3 +517,31 @@ func (r RedirectToHTTPS) ServeHTTP(w http.ResponseWriter, req *http.Request) {
url.Host = url.Hostname() // strip the port if one exists
http.Redirect(w, req, url.String(), http.StatusSeeOther)
}

type SizeTrackerHTTPResponseWriter struct {
http.ResponseWriter
bytesRead *atomic.Uint64
}

func NewSizeTrackerHTTPResponseWriter(w http.ResponseWriter) SizeTrackerHTTPResponseWriter {
return SizeTrackerHTTPResponseWriter{
ResponseWriter: w,
bytesRead: &atomic.Uint64{},
}
}

func (w SizeTrackerHTTPResponseWriter) Write(input []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(input)
w.bytesRead.Add(uint64(n))
return
}

func (w SizeTrackerHTTPResponseWriter) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}

func (w SizeTrackerHTTPResponseWriter) BytesRead() uint64 {
return w.bytesRead.Load()
}

0 comments on commit 5aab2c4

Please sign in to comment.