http.go 806 B

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