close http server properly

pull/700/head
Darien Raymond 2017-11-09 01:06:40 +01:00
parent 66b82e4ab7
commit 6e61538b36
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
1 changed files with 12 additions and 7 deletions

View File

@ -10,9 +10,10 @@ type Server struct {
Port net.Port Port net.Port
PathHandler map[string]http.HandlerFunc PathHandler map[string]http.HandlerFunc
accepting bool accepting bool
server *http.Server
} }
func (server *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) { func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/" { if req.URL.Path == "/" {
resp.Header().Set("Content-Type", "text/plain; charset=utf-8") resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
resp.WriteHeader(http.StatusOK) resp.WriteHeader(http.StatusOK)
@ -20,17 +21,21 @@ func (server *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
return return
} }
handler, found := server.PathHandler[req.URL.Path] handler, found := s.PathHandler[req.URL.Path]
if found { if found {
handler(resp, req) handler(resp, req)
} }
} }
func (server *Server) Start() (net.Destination, error) { func (s *Server) Start() (net.Destination, error) {
go http.ListenAndServe("127.0.0.1:"+server.Port.String(), server) s.server = &http.Server{
return net.TCPDestination(net.LocalHostIP, net.Port(server.Port)), nil Addr: "127.0.0.1:" + s.Port.String(),
Handler: s,
}
go s.server.ListenAndServe()
return net.TCPDestination(net.LocalHostIP, net.Port(s.Port)), nil
} }
func (v *Server) Close() { func (s *Server) Close() {
v.accepting = false s.server.Close()
} }