-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.go
70 lines (58 loc) · 1 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
package smux
import (
"bufio"
"bytes"
"io"
)
type Server struct {
Network string
Address string
Handler Handler
}
func (s Server) ListenAndServe() error {
l, err := Listen(s.Network, s.Address)
if err != nil {
return err
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
return err
}
defer conn.Close()
go conn.Listen()
go func() {
for {
stream, err := conn.Accept()
if err != nil {
break
}
go func() {
go stream.Poll()
var buf bytes.Buffer
out := make([]byte, 512)
for {
n, err := stream.Read(out)
if err == io.EOF {
break
}
buf.Write(out[:n])
}
var b bytes.Buffer
w := bufio.NewWriter(&b)
s.Handler.Serve(w, bytes.NewReader(buf.Bytes()))
w.Flush()
stream.WriteOnce(b.Bytes())
}()
}
}()
}
}
type Handler interface {
Serve(io.Writer, io.Reader)
}
type HandlerFunc func(io.Writer, io.Reader)
func (f HandlerFunc) Serve(w io.Writer, r io.Reader) {
f(w, r)
}