File: response_writer.go

package info (click to toggle)
golang-github-miolini-datacounter 1.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 100 kB
  • sloc: makefile: 2
file content (64 lines) | stat: -rw-r--r-- 1,755 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
package datacounter

import (
	"bufio"
	"fmt"
	"net"
	"net/http"
	"sync/atomic"
	"time"
)

// ResponseWriterCounter is counter for http.ResponseWriter
type ResponseWriterCounter struct {
	http.ResponseWriter
	count      uint64
	started    time.Time
	statusCode int
}

// NewResponseWriterCounter function create new ResponseWriterCounter
func NewResponseWriterCounter(rw http.ResponseWriter) *ResponseWriterCounter {
	return &ResponseWriterCounter{
		ResponseWriter: rw,
		started:        time.Now(),
	}
}

// Write returns underlying Write result, while counting data size
func (counter *ResponseWriterCounter) Write(buf []byte) (int, error) {
	n, err := counter.ResponseWriter.Write(buf)
	atomic.AddUint64(&counter.count, uint64(n))
	return n, err
}

// Header returns underlying Header result
func (counter *ResponseWriterCounter) Header() http.Header {
	return counter.ResponseWriter.Header()
}

// WriteHeader returns underlying WriteHeader, while setting Runtime header
func (counter *ResponseWriterCounter) WriteHeader(statusCode int) {
	counter.Header().Set("X-Runtime", fmt.Sprintf("%.6f", time.Since(counter.started).Seconds()))
	counter.ResponseWriter.WriteHeader(statusCode)
}

// Hijack returns underlying Hijack
func (counter *ResponseWriterCounter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	return counter.ResponseWriter.(http.Hijacker).Hijack()
}

// Count function return counted bytes
func (counter *ResponseWriterCounter) Count() uint64 {
	return atomic.LoadUint64(&counter.count)
}

// Started returns started value
func (counter *ResponseWriterCounter) Started() time.Time {
	return counter.started
}

// StatusCode returns sent status code
func (counter *ResponseWriterCounter) StatusCode() int {
	return counter.statusCode
}