github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/testing/servers/http/http.go (about)

     1  package tcp
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/xmplusdev/xmcore/common/net"
     7  )
     8  
     9  type Server struct {
    10  	Port        net.Port
    11  	PathHandler map[string]http.HandlerFunc
    12  	server      *http.Server
    13  }
    14  
    15  func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
    16  	if req.URL.Path == "/" {
    17  		resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
    18  		resp.WriteHeader(http.StatusOK)
    19  		resp.Write([]byte("Home"))
    20  		return
    21  	}
    22  
    23  	handler, found := s.PathHandler[req.URL.Path]
    24  	if found {
    25  		handler(resp, req)
    26  	}
    27  }
    28  
    29  func (s *Server) Start() (net.Destination, error) {
    30  	s.server = &http.Server{
    31  		Addr:    "127.0.0.1:" + s.Port.String(),
    32  		Handler: s,
    33  	}
    34  	go s.server.ListenAndServe()
    35  	return net.TCPDestination(net.LocalHostIP, s.Port), nil
    36  }
    37  
    38  func (s *Server) Close() error {
    39  	return s.server.Close()
    40  }