|
|
@ -6,7 +6,7 @@ import ( |
|
|
|
"net" |
|
|
|
"net" |
|
|
|
"net/http" |
|
|
|
"net/http" |
|
|
|
"net/url" |
|
|
|
"net/url" |
|
|
|
"strings" |
|
|
|
"sync" |
|
|
|
"time" |
|
|
|
"time" |
|
|
|
|
|
|
|
|
|
|
|
ic "github.com/go-kratos/kratos/v2/internal/context" |
|
|
|
ic "github.com/go-kratos/kratos/v2/internal/context" |
|
|
@ -56,6 +56,8 @@ type Server struct { |
|
|
|
*http.Server |
|
|
|
*http.Server |
|
|
|
ctx context.Context |
|
|
|
ctx context.Context |
|
|
|
lis net.Listener |
|
|
|
lis net.Listener |
|
|
|
|
|
|
|
once sync.Once |
|
|
|
|
|
|
|
err error |
|
|
|
network string |
|
|
|
network string |
|
|
|
address string |
|
|
|
address string |
|
|
|
endpoint *url.URL |
|
|
|
endpoint *url.URL |
|
|
@ -112,35 +114,33 @@ func (s *Server) ServeHTTP(res http.ResponseWriter, req *http.Request) { |
|
|
|
// examples:
|
|
|
|
// examples:
|
|
|
|
// http://127.0.0.1:8000?isSecure=false
|
|
|
|
// http://127.0.0.1:8000?isSecure=false
|
|
|
|
func (s *Server) Endpoint() (*url.URL, error) { |
|
|
|
func (s *Server) Endpoint() (*url.URL, error) { |
|
|
|
if s.lis == nil && strings.HasSuffix(s.address, ":0") { |
|
|
|
s.once.Do(func() { |
|
|
|
lis, err := net.Listen(s.network, s.address) |
|
|
|
lis, err := net.Listen(s.network, s.address) |
|
|
|
if err != nil { |
|
|
|
if err != nil { |
|
|
|
return nil, err |
|
|
|
s.err = err |
|
|
|
} |
|
|
|
return |
|
|
|
s.lis = lis |
|
|
|
|
|
|
|
} |
|
|
|
} |
|
|
|
addr, err := host.Extract(s.address, s.lis) |
|
|
|
addr, err := host.Extract(s.address, s.lis) |
|
|
|
if err != nil { |
|
|
|
if err != nil { |
|
|
|
return nil, err |
|
|
|
lis.Close() |
|
|
|
|
|
|
|
s.err = err |
|
|
|
|
|
|
|
return |
|
|
|
} |
|
|
|
} |
|
|
|
u := &url.URL{ |
|
|
|
s.lis = lis |
|
|
|
Scheme: "http", |
|
|
|
s.endpoint = &url.URL{Scheme: "http", Host: addr} |
|
|
|
Host: addr, |
|
|
|
}) |
|
|
|
|
|
|
|
if s.err != nil { |
|
|
|
|
|
|
|
return nil, s.err |
|
|
|
} |
|
|
|
} |
|
|
|
s.endpoint = u |
|
|
|
return s.endpoint, nil |
|
|
|
return u, nil |
|
|
|
|
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// Start start the HTTP server.
|
|
|
|
// Start start the HTTP server.
|
|
|
|
func (s *Server) Start(ctx context.Context) error { |
|
|
|
func (s *Server) Start(ctx context.Context) error { |
|
|
|
s.ctx = ctx |
|
|
|
if _, err := s.Endpoint(); err != nil { |
|
|
|
if s.lis == nil { |
|
|
|
|
|
|
|
lis, err := net.Listen(s.network, s.address) |
|
|
|
|
|
|
|
if err != nil { |
|
|
|
|
|
|
|
return err |
|
|
|
return err |
|
|
|
} |
|
|
|
} |
|
|
|
s.lis = lis |
|
|
|
s.ctx = ctx |
|
|
|
} |
|
|
|
|
|
|
|
s.log.Infof("[HTTP] server listening on: %s", s.lis.Addr().String()) |
|
|
|
s.log.Infof("[HTTP] server listening on: %s", s.lis.Addr().String()) |
|
|
|
if err := s.Serve(s.lis); !errors.Is(err, http.ErrServerClosed) { |
|
|
|
if err := s.Serve(s.lis); !errors.Is(err, http.ErrServerClosed) { |
|
|
|
return err |
|
|
|
return err |
|
|
|