File: httpresponsestatus.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (76 lines) | stat: -rw-r--r-- 1,720 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package missinggo

// todo move to httptoo as ResponseRecorder

import (
	"bufio"
	"net"
	"net/http"
	"time"
)

// A http.ResponseWriter that tracks the status of the response. The status
// code, and number of bytes written for example.
type StatusResponseWriter struct {
	http.ResponseWriter
	Code            int
	BytesWritten    int64
	Started         time.Time
	TimeToFirstByte time.Duration // Time to first byte
	GotFirstByte    bool
	WroteHeader     Event
	Hijacked        bool
}

var _ interface {
	http.ResponseWriter
	http.Hijacker
} = (*StatusResponseWriter)(nil)

func (me *StatusResponseWriter) Write(b []byte) (n int, err error) {
	// Exactly how it's done in the standard library. This ensures Code is
	// correct.
	if !me.WroteHeader.IsSet() {
		me.WriteHeader(http.StatusOK)
	}
	if me.Started.IsZero() {
		panic("Started was not initialized")
	}
	timeBeforeWrite := time.Now()
	n, err = me.ResponseWriter.Write(b)
	if n > 0 && !me.GotFirstByte {
		me.TimeToFirstByte = timeBeforeWrite.Sub(me.Started)
		me.GotFirstByte = true
	}
	me.BytesWritten += int64(n)
	return
}

func (me *StatusResponseWriter) WriteHeader(code int) {
	me.ResponseWriter.WriteHeader(code)
	if !me.WroteHeader.IsSet() {
		me.Code = code
		me.WroteHeader.Set()
	}
}

func (me *StatusResponseWriter) Hijack() (c net.Conn, b *bufio.ReadWriter, err error) {
	me.Hijacked = true
	c, b, err = me.ResponseWriter.(http.Hijacker).Hijack()
	if b.Writer.Buffered() != 0 {
		panic("unexpected buffered writes")
	}
	c = responseConn{c, me}
	return
}

type responseConn struct {
	net.Conn
	s *StatusResponseWriter
}

func (me responseConn) Write(b []byte) (n int, err error) {
	n, err = me.Conn.Write(b)
	me.s.BytesWritten += int64(n)
	return
}