-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpproxy.go
More file actions
73 lines (62 loc) · 1.38 KB
/
httpproxy.go
File metadata and controls
73 lines (62 loc) · 1.38 KB
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
package ttproxy
import (
"fmt"
"io"
"log/slog"
"net/http"
)
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// only handle HTTP CONNNECT method
// ignore other HTTP method
if r.Method != http.MethodConnect {
// slog.Error("http method error: %v" + r.Method)
srv.httpMux.ServeHTTP(w, r)
return
}
w.WriteHeader(http.StatusOK)
rc := http.NewResponseController(w)
err := rc.Flush()
if err != nil {
slog.Error(fmt.Sprintf("flush response writer error: %v", err))
return
}
conn, bfw, err := rc.Hijack()
if err != nil {
slog.Error(fmt.Sprintf("hijack error: %v", err))
return
}
hostPort := r.URL.Host
if hostPort == "" {
hostPort = r.Host
}
slog.Info(fmt.Sprintf("receive new http proxy TCP connection %s <---> %s", conn.RemoteAddr().String(), hostPort))
rconn, err := srv.Dial("tcp", hostPort)
if err != nil {
return
}
defer rconn.Close()
// write all buffered bytes into remote connection
if n := bfw.Reader.Buffered(); n > 0 {
bb, err := bfw.Reader.Peek(n)
if err != nil {
return
}
_, err = rconn.Write(bb)
if err != nil {
return
}
}
done := make(chan struct{})
go func() {
io.Copy(rconn, conn)
if cw, ok := rconn.(interface{ CloseWrite() error }); ok {
cw.CloseWrite()
}
done <- struct{}{}
}()
io.Copy(conn, rconn)
if cw, ok := conn.(interface{ CloseWrite() error }); ok {
cw.CloseWrite()
}
<-done
}