-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathresponse.go
89 lines (76 loc) · 2.1 KB
/
response.go
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
77
78
79
80
81
82
83
84
85
86
87
88
89
package frodo
import (
"bufio"
"errors"
"net"
"net/http"
"time"
"log"
)
const customErrorMessage string = "[ERROR] Headers were already written."
// ResponseWriter is used to hijack/embed http.ResponseWriter
// thus making it satisfy the ResponseWriter interface, we then add a written boolean property
// to trace when a write made, with a couple of other helpful properties
type ResponseWriter struct {
http.ResponseWriter
headerWritten bool
written bool
timeStart time.Time
timeEnd time.Time
duration float64
statusCode int
size int64
method string
route string
}
// Write writes data back the client/creates the body
func (w *ResponseWriter) Write(bytes []byte) (int, error) {
if !w.HeaderWritten() {
w.WriteHeader(http.StatusOK)
}
if w.ResponseSent() {
log.Println(customErrorMessage)
return 1, errors.New(customErrorMessage)
}
sent, err := w.ResponseWriter.Write(bytes)
if err != nil {
return sent, err
}
w.size += int64(sent)
w.timeEnd = time.Now()
w.duration = time.Since(w.timeEnd).Seconds()
return sent, nil
}
// WriteHeader writes the Headers out
func (w *ResponseWriter) WriteHeader(code int) {
if w.HeaderWritten() {
log.Println(customErrorMessage)
return
}
w.ResponseWriter.WriteHeader(code)
w.headerWritten = true
w.statusCode = code
}
// ResponseSent checks if a write has been made
// starts with a header being sent out
func (w *ResponseWriter) ResponseSent() bool {
return w.written
}
// HeaderWritten checks if a write has been made
// starts with a header being sent out
func (w *ResponseWriter) HeaderWritten() bool {
return w.headerWritten
}
// Hijack wraps response writer's Hijack function.
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}
// CloseNotify wraps response writer's CloseNotify function.
func (w *ResponseWriter) CloseNotify() <-chan bool {
return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
// Size returns the size of the response
// about to be sent out
func (w *ResponseWriter) Size() int64 {
return w.size
}