This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_server_test.go
135 lines (102 loc) · 2.08 KB
/
example_server_test.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
package tcp_test
import (
"context"
"errors"
"io"
"log"
"net"
"time"
"github.com/hamba/tcp"
)
type ResponseWriter interface {
io.Writer
}
type Request struct {
Body io.Reader
Close bool
}
type Handler interface {
ServeTCP(w ResponseWriter, r *Request)
}
type HandlerFunc func(w ResponseWriter, r *Request)
func (fn HandlerFunc) ServeTCP(w ResponseWriter, r *Request) {
fn(w, r)
}
type serverCodec struct {
server *Server
conn io.ReadWriter
}
func (c *serverCodec) Handle(ctx context.Context, deadline tcp.SetWriteDeadline) bool {
req := &Request{Body: c.conn}
if d := c.server.WriteTimeout; d > 0 {
deadline(time.Now().Add(d))
}
c.server.Handler.ServeTCP(c.conn, req)
return req.Close
}
func (c *serverCodec) Close() error {
return nil
}
type Server struct {
Addr string
Handler Handler
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
srv *tcp.Server
}
func (s *Server) ListenAndServe() error {
addr := s.Addr
if addr == "" {
addr = ":8080"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return s.Serve(ln)
}
func (s *Server) Serve(ln net.Listener) error {
if s.Handler == nil {
return errors.New("server: handler cannot be nil")
}
if s.srv == nil {
srv, err := tcp.NewServer(s.createCodec, tcp.ServerOpts{
ReadTimeout: s.ReadTimeout,
IdleTimeout: s.IdleTimeout,
})
if err != nil {
return err
}
s.srv = srv
}
return s.srv.Serve(ln)
}
func (s *Server) createCodec(conn io.ReadWriter) tcp.ServerCodec {
return &serverCodec{
server: s,
conn: conn,
}
}
func (s *Server) Shutdown(ctx context.Context) error {
return s.srv.Shutdown(ctx)
}
func (s *Server) Close() error {
return s.srv.Close()
}
func ExampleServer() {
h := HandlerFunc(func(w ResponseWriter, r *Request) {
// Do your read and write here
})
srv := &Server{
Addr: "localhost:80",
Handler: h,
ReadTimeout: 100 * time.Millisecond,
WriteTimeout: 100 * time.Millisecond,
IdleTimeout: 10 * time.Second,
}
defer srv.Close()
if err := srv.ListenAndServe(); err != nil {
log.Print(err)
}
}