forked from osiloke/go-http-tunnel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
78 lines (64 loc) · 1.21 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
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tunnel
import (
"io"
"net/http"
"github.com/mmatczuk/go-http-tunnel/log"
)
type closeWriter interface {
CloseWrite() error
}
type closeReader interface {
CloseRead() error
}
func transfer(dst io.Writer, src io.ReadCloser, logger log.Logger) {
n, err := io.Copy(dst, src)
if err != nil {
logger.Log(
"level", 2,
"msg", "copy error",
"err", err,
)
}
if d, ok := dst.(closeWriter); ok {
d.CloseWrite()
}
if s, ok := src.(closeReader); ok {
s.CloseRead()
} else {
src.Close()
}
logger.Log(
"level", 3,
"action", "transferred",
"bytes", n,
)
}
func copyHeader(dst, src http.Header) {
for k, v := range src {
vv := make([]string, len(v))
copy(vv, v)
dst[k] = vv
}
}
type countWriter struct {
w io.Writer
count int64
}
func (cw *countWriter) Write(p []byte) (n int, err error) {
n, err = cw.w.Write(p)
cw.count += int64(n)
return
}
type flushWriter struct {
w io.Writer
}
func (fw flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.w.Write(p)
if f, ok := fw.w.(http.Flusher); ok {
f.Flush()
}
return
}