-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
74 lines (58 loc) · 1.32 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
package poteto
import (
"net/http"
"github.com/poteto-go/poteto/utils"
)
type Response interface {
WriteHeader(code int)
Write(b []byte) (int, error)
SetStatus(code int)
Header() http.Header
SetHeader(key, value string)
AddHeader(key, value string)
}
type response struct {
Writer http.ResponseWriter
Status int
Size int64
IsCommitted bool
}
func NewResponse(w http.ResponseWriter) Response {
return &response{Writer: w}
}
func (r *response) WriteHeader(code int) {
if r.IsCommitted {
utils.PotetoPrint("response has already committed\n")
return
}
r.SetStatus(code)
r.Writer.WriteHeader(r.Status)
r.IsCommitted = true
}
func (r *response) SetHeader(key, value string) {
if r.Writer.Header().Get(key) != "" {
return
}
r.Writer.Header().Set(key, value)
}
func (r *response) AddHeader(key, value string) {
r.Writer.Header().Add(key, value)
}
func (r *response) Write(b []byte) (int, error) {
if !r.IsCommitted {
if r.Status == 0 {
r.SetStatus(http.StatusOK)
}
r.WriteHeader(r.Status)
r.IsCommitted = true
}
n, err := r.Writer.Write(b)
r.Size += int64(n)
return n, err
}
func (r *response) SetStatus(code int) {
r.Status = code
}
func (r *response) Header() http.Header {
return r.Writer.Header()
}