diff options
Diffstat (limited to 'pkg/worker/http.go')
-rw-r--r-- | pkg/worker/http.go | 49 |
1 files changed, 43 insertions, 6 deletions
diff --git a/pkg/worker/http.go b/pkg/worker/http.go index 973775e..c4f9950 100644 --- a/pkg/worker/http.go +++ b/pkg/worker/http.go @@ -2,24 +2,41 @@ package worker import ( "context" + "errors" + "net" "net/http" + "net/url" +) + +var ( + UnsupportedSchemeErr = errors.New("Ivalid schema, only tcp and unix supported") ) type ServerTask struct { - server *http.Server + addr string + handler http.Handler } -func NewServerTask(server *http.Server) *ServerTask { +func NewServerTask(addr string, handler http.Handler) *ServerTask { return &ServerTask{ - server: server, + addr: addr, + handler: handler, } } -func (self *ServerTask) Start(ctx context.Context) error { +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 <- self.server.ListenAndServe() + done <- server.Serve(listen) }() select { @@ -33,6 +50,26 @@ func (self *ServerTask) Start(ctx context.Context) error { // shutdown, and return its error, which is most cases, but not limited, is // context.Canceled. case <-ctx.Done(): - return self.server.Shutdown(ctx) + 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 } } |