1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 02:17:05 +00:00

accesslog middleware: add total bytes received and sent

relative to: https://github.com/kataras/iris/issues/1601
This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-09-08 13:44:50 +03:00
parent a4996b90c8
commit d6867e1f9e
7 changed files with 223 additions and 53 deletions

View File

@@ -1,8 +1,13 @@
package context
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/textproto"
"strconv"
"sync"
)
@@ -38,6 +43,8 @@ type ResponseRecorder struct {
chunks []byte
// the saved headers
headers http.Header
result *http.Response
}
var _ ResponseWriter = (*ResponseRecorder)(nil)
@@ -53,6 +60,7 @@ func (w *ResponseRecorder) Naive() http.ResponseWriter {
func (w *ResponseRecorder) BeginRecord(underline ResponseWriter) {
w.ResponseWriter = underline
w.headers = underline.Header()
w.result = nil
w.ResetBody()
}
@@ -288,3 +296,66 @@ func (w *ResponseRecorder) Push(target string, opts *http.PushOptions) (err erro
return ErrPushNotSupported
}
// Result returns the response generated by the handler.
// It does set all provided headers.
//
// Result must only be called after the handler has finished running.
func (w *ResponseRecorder) Result() *http.Response { // a modified copy of net/http/httptest
if w.result != nil {
return w.result
}
headers := w.headers.Clone()
for k, v := range w.ResponseWriter.Header() {
headers[k] = v
}
/*
dateFound := false
for k := range headers {
if strings.ToLower(k) == "date" {
dateFound = true
break
}
}
if !dateFound {
headers["Date"] = []string{time.Now().Format(http.TimeFormat)}
}
*/
res := &http.Response{
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: w.StatusCode(),
Header: headers,
}
if res.StatusCode == 0 {
res.StatusCode = 200
}
res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
if w.chunks != nil {
res.Body = ioutil.NopCloser(bytes.NewReader(w.chunks))
} else {
res.Body = http.NoBody
}
res.ContentLength = parseContentLength(res.Header.Get("Content-Length"))
w.result = res
return res
}
// copy of net/http/httptest
func parseContentLength(cl string) int64 {
cl = textproto.TrimString(cl)
if cl == "" {
return -1
}
n, err := strconv.ParseUint(cl, 10, 63)
if err != nil {
return -1
}
return int64(n)
}