package server import ( "context" "fmt" "net" "net/http" logger "git.pyer.club/kingecg/gologger" "github.com/soheilhy/cmux" ) var ServerManager map[string]*ServerListener = make(map[string]*ServerListener) type ServerListener struct { listener cmux.CMux servers map[string]*http.Server } func (s *ServerListener) AddServer(name string, server *http.Server) { s.servers[name] = server } func (s *ServerListener) StartServer(name string) error { server, ok := s.servers[name] if !ok { panic("No named server") } l := s.listener.Match(cmux.HTTP1HeaderField("Host", name)) return server.Serve(l) } func (s *ServerListener) Start() { for name, _ := range s.servers { err := s.StartServer(name) if err != nil { l := logger.GetLogger("ServerListener") l.Error("Start server error:", name, err) } } } func (s *ServerListener) ShutDown() { // may need add wait group for _, server := range s.servers { server.Shutdown(context.Background()) } } func (s *ServerListener) Serve() { go s.listener.Serve() } func NewServerListener(port int) *ServerListener { listenStr := fmt.Sprintf(":%d", port) l, err := net.Listen("tcp", listenStr) if err != nil { l := logger.GetLogger("ServerListener") l.Error("Listen error:", err) } muxer := cmux.New(l) s := &ServerListener{listener: muxer, servers: make(map[string]*http.Server)} return s }