git » gofer » commit d5c8f6f

http: Implement statusWriter.ReadFrom to enable sendfile

author Alberto Bertogli
2020-06-09 11:03:35 UTC
committer Alberto Bertogli
2020-06-09 23:49:32 UTC
parent b95a0baa51f4a3d12d87f2a7e0e6116954cab8fb

http: Implement statusWriter.ReadFrom to enable sendfile

Go can transparently use the sendfile syscall to serve files, which can
be a large performance improvement; however this only happens if,
amongst other things, the response writer has a ReadFrom method.

This patch implements that ReadFrom method in statusWriter so it works
with sendfile, which yields a ~50% performance improvement for common
conditions such as file serving.

server/http.go +9 -0

diff --git a/server/http.go b/server/http.go
index 2dafe3e..f104d9e 100644
--- a/server/http.go
+++ b/server/http.go
@@ -5,6 +5,7 @@ import (
 	"crypto/tls"
 	"errors"
 	"fmt"
+	"io"
 	golog "log"
 	"net/http"
 	"net/http/cgi"
@@ -418,6 +419,14 @@ func (w *statusWriter) Write(b []byte) (int, error) {
 	return n, err
 }
 
+// ReadFrom is optional but enables the use of sendfile, which speeds things
+// up considerably.
+func (w *statusWriter) ReadFrom(src io.Reader) (int64, error) {
+	n, err := io.Copy(w.ResponseWriter, src)
+	w.length += n
+	return n, err
+}
+
 func SetHeader(parent http.Handler, hdrs map[string]string) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		tr, _ := trace.FromContext(r.Context())