forked from go-httpproxy/httpproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
157 lines (148 loc) · 3.46 KB
/
utils.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package httpproxy
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"regexp"
"strconv"
"strings"
"time"
)
// InMemoryResponse creates new HTTP response given arguments.
func InMemoryResponse(code int, header http.Header, body []byte) *http.Response {
if header == nil {
header = make(http.Header)
}
st := http.StatusText(code)
if st != "" {
st = " " + st
}
var bodyReadCloser io.ReadCloser
var bodyContentLength = int64(0)
if body != nil {
bodyReadCloser = ioutil.NopCloser(bytes.NewBuffer(body))
bodyContentLength = int64(len(body))
}
return &http.Response{
Status: fmt.Sprintf("%d%s", code, st),
StatusCode: code,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: header,
Body: bodyReadCloser,
ContentLength: bodyContentLength,
}
}
// ServeResponse serves HTTP response to http.ResponseWriter.
func ServeResponse(w http.ResponseWriter, resp *http.Response) error {
if resp.Body != nil {
defer resp.Body.Close()
}
h := w.Header()
for k, v := range resp.Header {
for _, v1 := range v {
h.Add(k, v1)
}
}
if h.Get("Date") == "" {
h.Set("Date", time.Now().UTC().Format("Mon, 2 Jan 2006 15:04:05")+" GMT")
}
if h.Get("Content-Type") == "" && resp.ContentLength != 0 {
h.Set("Content-Type", "text/plain; charset=utf-8")
}
if resp.ContentLength >= 0 {
h.Set("Content-Length", strconv.FormatInt(resp.ContentLength, 10))
} else {
h.Del("Content-Length")
}
h.Del("Transfer-Encoding")
te := ""
if len(resp.TransferEncoding) > 0 {
if len(resp.TransferEncoding) > 1 {
return ErrUnsupportedTransferEncoding
}
te = resp.TransferEncoding[0]
}
h.Del("Connection")
clientConnection := ""
if resp.Request != nil {
clientConnection = resp.Request.Header.Get("Connection")
}
switch clientConnection {
case "close":
h.Set("Connection", "close")
case "keep-alive":
if h.Get("Content-Length") != "" || te == "chunked" {
h.Set("Connection", "keep-alive")
} else {
h.Set("Connection", "close")
}
default:
if te == "chunked" {
h.Set("Connection", "close")
}
}
switch te {
case "":
w.WriteHeader(resp.StatusCode)
if resp.Body != nil {
if _, err := io.Copy(w, resp.Body); err != nil {
return err
}
}
case "chunked":
h.Set("Transfer-Encoding", "chunked")
w.WriteHeader(resp.StatusCode)
w2 := httputil.NewChunkedWriter(w)
if resp.Body != nil {
if _, err := io.Copy(w2, resp.Body); err != nil {
return err
}
}
if err := w2.Close(); err != nil {
return err
}
if _, err := w.Write([]byte("\r\n")); err != nil {
return err
}
default:
return ErrUnsupportedTransferEncoding
}
return nil
}
// ServeInMemory serves HTTP response given arguments to http.ResponseWriter.
func ServeInMemory(w http.ResponseWriter, code int, header http.Header, body []byte) error {
return ServeResponse(w, InMemoryResponse(code, header, body))
}
var hasPort = regexp.MustCompile(`:\d+$`)
func stripPort(s string) string {
ix := strings.IndexRune(s, ':')
if ix == -1 {
return s
}
return s[:ix]
}
func GetFreePort() (port int, err error) {
var a *net.TCPAddr
if a, err = net.ResolveTCPAddr("tcp", "0.0.0.0:0"); err == nil {
var l *net.TCPListener
if l, err = net.ListenTCP("tcp", a); err == nil {
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
}
return
}
func CheckFreePort(port int) bool {
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return false
}
ln.Close()
return true
}