This repository has been archived by the owner on Jan 13, 2023. It is now read-only.
/
server.go
86 lines (73 loc) · 1.61 KB
/
server.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
package main
import (
"fmt"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/payfazz/go-errors"
"github.com/payfazz/go-errors/errhandler"
"github.com/payfazz/ioconn"
"github.com/payfazz/mainutil"
"github.com/payfazz/stdlog"
"golang.org/x/net/http2"
)
func runServer(addr string) {
netaddr := strings.SplitN(addr, ":", 2)
if len(netaddr) != 2 {
showUsage()
}
leftListener, err := net.Listen(netaddr[0], netaddr[1])
errhandler.Check(errors.Wrap(err))
stdlog.E(fmt.Sprintf("Server listening on %v\n", leftListener.Addr()))
wrappedStdin := newEOFNotifier(os.Stdin)
stdinClosedCh := wrappedStdin.ch()
rightMuxed := ioconn.New(ioconn.Config{
Reader: wrappedStdin,
Writer: os.Stdout,
})
go func() {
<-stdinClosedCh
leftListener.Close()
}()
rightMuxedConn, err := (&http2.Transport{}).NewClientConn(rightMuxed)
errhandler.Check(errors.Wrap(err))
mainloop:
for {
left, err := leftListener.Accept()
if err != nil {
select {
case <-stdinClosedCh:
break mainloop
default:
mainutil.Eprint(errors.Wrap(err))
time.Sleep(1 * time.Second)
continue mainloop
}
}
go func() {
defer errhandler.With(mainutil.Eprint)
defer left.Close()
rightReq := &http.Request{
Method: "POST",
URL: &url.URL{
Scheme: "http",
Path: "/",
},
Body: left,
}
rightResp, err := rightMuxedConn.RoundTrip(rightReq)
errhandler.Check(errors.Wrap(err))
defer rightResp.Body.Close()
if err := copyAll(rightResp.Body, left); err != nil {
select {
case <-stdinClosedCh:
default:
mainutil.Eprint(errors.Wrap(err))
}
}
}()
}
}