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
|
package worker
import (
"context"
"errors"
"net"
"net/http"
"net/url"
)
var (
UnsupportedSchemeErr = errors.New("Ivalid schema, only tcp and unix supported")
)
type ServerTask struct {
addr string
handler http.Handler
}
func NewServerTask(addr string, handler http.Handler) *ServerTask {
return &ServerTask{
addr: addr,
handler: handler,
}
}
func (s *ServerTask) Start(ctx context.Context) error {
done := make(chan error)
listen, err := getListen(s.addr)
if err != nil {
return err
}
server := &http.Server{
Handler: s.handler,
}
go func() {
done <- server.Serve(listen)
}()
select {
// if ListenAndServe error for something other than context.Canceled
//(e.g.: address already in use) it trigger done to return sonner with
// the return error
case err := <-done:
return err
// in case of context canceled it will manually trigger the server to
// shutdown, and return its error, which is most cases, but not limited, is
// context.Canceled.
case <-ctx.Done():
return server.Shutdown(ctx)
}
}
func getListen(addr string) (net.Listener, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
switch u.Scheme {
case "tcp":
return net.Listen(u.Scheme, u.Host)
case "unix":
host, err := url.JoinPath("/", u.Host, u.Path)
if err != nil {
return nil, err
}
return net.Listen(u.Scheme, host)
default:
return nil, UnsupportedSchemeErr
}
}
|