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
|
package httpserver
import (
"context"
"net"
"net/http"
"time"
)
const (
defaultReadTimeout = 10 * time.Second
defaultWriteTimeout = 10 * time.Second
defaultAddr = ":8080"
defaultShutdownTimeout = 3 * time.Second
)
// Server HTTP 服务
type Server struct {
server *http.Server
notify chan error
shutdownTimeout time.Duration
}
// NewServer 初始化并启动路由
func NewServer(handler http.Handler, opts ...Option) *Server {
httpSer := http.Server{
Addr: defaultAddr,
Handler: handler,
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
}
s := &Server{
server: &httpSer,
notify: make(chan error, 1),
shutdownTimeout: defaultShutdownTimeout,
}
for _, opt := range opts {
opt(s)
}
go s.start()
return s
}
func (s *Server) start() {
s.notify <- s.server.ListenAndServe()
close(s.notify)
}
// Notify .
func (s *Server) Notify() <-chan error {
return s.notify
}
// Shutdown 关闭服务
func (s *Server) Shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
defer cancel()
return s.server.Shutdown(ctx)
}
// Option 修改 server 相关参数
type Option func(*Server)
// Port 修改端口
func Port(v string) Option {
return func(s *Server) {
s.server.Addr = net.JoinHostPort("", v)
}
}
|