-
Notifications
You must be signed in to change notification settings - Fork 14
/
net.go
87 lines (74 loc) · 2.06 KB
/
net.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
// Copyright (c) 2020 Meng Huang ([email protected])
// This package is licensed under a MIT license that can be found in the LICENSE file.
package netpoll
import (
"errors"
"io"
"net"
"syscall"
)
const (
bufferSize = 0x10000
)
// EOF is the error returned by Read when no more input is available.
var EOF = io.EOF
// EAGAIN is the error when resource temporarily unavailable
var EAGAIN = syscall.EAGAIN
// ErrServerClosed is returned by the Server's Serve and ListenAndServe
// methods after a call to Close.
var ErrServerClosed = errors.New("Server closed")
// ErrHandler is the error when the Handler is nil
var ErrHandler = errors.New("Handler must be not nil")
// ErrListener is the error when the Listener is nil
var ErrListener = errors.New("Listener must be not nil")
// ListenAndServe listens on the network address and then calls
// Serve with handler to handle requests on incoming connections.
//
// The handler must be not nil.
//
// ListenAndServe always returns a non-nil error.
func ListenAndServe(network, address string, handler Handler) error {
server := &Server{Network: network, Address: address, Handler: handler}
return server.ListenAndServe()
}
// Serve accepts incoming connections on the listener l,
// and registers the conn fd to poll. The poll will trigger the fd to
// read requests and then call handler to reply to them.
//
// The handler must be not nil.
//
// Serve always returns a non-nil error.
func Serve(lis net.Listener, handler Handler) error {
server := &Server{Handler: handler}
return server.Serve(lis)
}
type netServer struct {
listener net.Listener
Handler Handler
}
func (s *netServer) Serve(l net.Listener) (err error) {
s.listener = l
for {
var conn net.Conn
conn, err = s.listener.Accept()
if err != nil {
break
}
go func(c net.Conn) {
var err error
var context Context
if context, err = s.Handler.Upgrade(c); err != nil {
c.Close()
return
}
for err == nil {
err = s.Handler.Serve(context)
}
c.Close()
}(conn)
}
return
}
func (s *netServer) Close() error {
return s.listener.Close()
}