// NewServer creates a new Server instance that will listen on addr
// and will serve the sites configured in group.
976885
func NewServer(addr string, group []*SiteConfig) (*Server, error) {
	s := &Server{
		Server:      makeHTTPServer(addr, group),
		vhosts:      newVHostTrie(),
		sites:       group,
		connTimeout: GracefulTimeout,
	}
	s.Server.Handler = s // this is weird, but whatever
	s.Server.ConnState = func(c net.Conn, cs http.ConnState) {
		if cs == http.StateIdle {
			s.listenerMu.Lock()
			// server stopped, close idle connection
			if s.listener == nil {
				c.Close()
			}
			s.listenerMu.Unlock()
		}
	}

	// Disable HTTP/2 if desired
	if !HTTP2 {
		s.Server.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
	}

	// Enable QUIC if desired
	if QUIC {
		s.quicServer = &h2quic.Server{Server: s.Server}
		s.Server.Handler = s.wrapWithSvcHeaders(s.Server.Handler)
	}

	// We have to bound our wg with one increment
	// to prevent a "race condition" that is hard-coded
	// into sync.WaitGroup.Wait() - basically, an add
	// with a positive delta must be guaranteed to
	// occur before Wait() is called on the wg.
	// In a way, this kind of acts as a safety barrier.
	s.connWg.Add(1)

	// Set up TLS configuration
	var tlsConfigs []*caddytls.Config
	for _, site := range group {
		tlsConfigs = append(tlsConfigs, site.TLS)
	}
	var err error
	s.Server.TLSConfig, err = caddytls.MakeTLSConfig(tlsConfigs)
	if err != nil {
		return nil, err
	}

	// As of Go 1.7, HTTP/2 is enabled only if NextProtos includes the string "h2"
	if HTTP2 && s.Server.TLSConfig != nil && len(s.Server.TLSConfig.NextProtos) == 0 {
		s.Server.TLSConfig.NextProtos = []string{"h2"}
	}

	// Compile custom middleware for every site (enables virtual hosting)
	for _, site := range group {
		stack := Handler(staticfiles.FileServer{Root: http.Dir(site.Root), Hide: site.HiddenFiles})
		for i := len(site.middleware) - 1; i >= 0; i-- {
			stack = site.middleware[i](stack)
		}
		site.middlewareChain = stack
		s.vhosts.Insert(site.Addr.VHost(), site)
	}

	return s, nil
}
607193
func NewServer(api *operations.MultiAuthExampleAPI) *Server {
	s := new(Server)

	s.shutdown = make(chan struct{})
	s.api = api
	s.interrupt = make(chan os.Signal, 1)
	return s
}
797699
func NewServer(t testing.TB, h http.Handler, client *http.Client) *Server {
	return newServer(t, httptest.NewServer(h), client)
}
934025
func NewServer(r *multichannel.Registrar, metricsProvider metrics.Provider, debug *localconfig.Debug, timeWindow time.Duration, mutualTLS bool) ab.AtomicBroadcastServer {
	s := &server{
		dh: deliver.NewHandler(deliverSupport{Registrar: r}, timeWindow, mutualTLS, deliver.NewMetrics(metricsProvider)),
		bh: &broadcast.Handler{
			SupportRegistrar: broadcastSupport{Registrar: r},
			Metrics:          broadcast.NewMetrics(metricsProvider),
		},
		debug:     debug,
		Registrar: r,
	}
	return s
}
901143
func NewServer(network *Network) *Server {
	s := &Server{
		router:  httprouter.New(),
		network: network,
	}

	s.OPTIONS("/", s.Options)
	s.GET("/", s.GetNetwork)
	s.POST("/start", s.StartNetwork)
	s.POST("/stop", s.StopNetwork)
	s.POST("/mocker/start", s.StartMocker)
	s.POST("/mocker/stop", s.StopMocker)
	s.GET("/mocker", s.GetMockers)
	s.POST("/reset", s.ResetNetwork)
	s.GET("/events", s.StreamNetworkEvents)
	s.GET("/snapshot", s.CreateSnapshot)
	s.POST("/snapshot", s.LoadSnapshot)
	s.POST("/nodes", s.CreateNode)
	s.GET("/nodes", s.GetNodes)
	s.GET("/nodes/:nodeid", s.GetNode)
	s.POST("/nodes/:nodeid/start", s.StartNode)
	s.POST("/nodes/:nodeid/stop", s.StopNode)
	s.POST("/nodes/:nodeid/conn/:peerid", s.ConnectNode)
	s.DELETE("/nodes/:nodeid/conn/:peerid", s.DisconnectNode)
	s.GET("/nodes/:nodeid/rpc", s.NodeRPC)

	return s
}
525696
func NewServer(ns string, kubeclientset kubernetes.Interface, appclientset appclientset.Interface, enf *rbac.Enforcer, projectLock *util.KeyLock, sessionMgr *session.SessionManager) *Server {
	auditLogger := argo.NewAuditLogger(ns, kubeclientset, "argocd-server")
	return &Server{enf: enf, appclientset: appclientset, kubeclientset: kubeclientset, ns: ns, projectLock: projectLock, auditLogger: auditLogger, sessionMgr: sessionMgr}
}
1320179
func NewServer(c Coser) http.Handler {
	ms := &server{
		Coser: c,
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/cos-n", ms.handleCosNQuery)
	mux.HandleFunc("/cos", ms.handleCosQuery)
	mux.HandleFunc("/coses", ms.handleCosesQuery)

	ms.ServeMux = mux
	return ms
}
317256
func NewServer(
	host HostInterface,
	resourceAnalyzer stats.ResourceAnalyzer,
	auth AuthInterface,
	enableDebuggingHandlers,
	enableContentionProfiling,
	redirectContainerStreaming bool,
	criHandler http.Handler) Server {
	server := Server{
		host:                       host,
		resourceAnalyzer:           resourceAnalyzer,
		auth:                       auth,
		restfulCont:                &filteringContainer{Container: restful.NewContainer()},
		redirectContainerStreaming: redirectContainerStreaming,
	}
	if auth != nil {
		server.InstallAuthFilter()
	}
	server.InstallDefaultHandlers()
	if enableDebuggingHandlers {
		server.InstallDebuggingHandlers(criHandler)
		if enableContentionProfiling {
			goruntime.SetBlockProfileRate(1)
		}
	} else {
		server.InstallDebuggingDisabledHandlers()
	}
	return server
}
11544
func NewServer(codec ServerCodec, defaultHandler interface{}) *Server {
	value := reflect.ValueOf(defaultHandler)
	if !validHandler(value, reflect.TypeOf(defaultHandler).Name()) {
		panic("NewServer: invalid default handler")
	}

	s := &Server{
		closed:  new(int32),
		rooms:   make(map[string]([]*Client)),
		roomsMu: new(sync.RWMutex),

		//Maps socket ID -> list of rooms the client is in
		joinedRooms:   make(map[string][]string),
		joinedRoomsMu: new(sync.RWMutex),

		handlers:     make(map[string]*regMethod),
		handlersLock: new(sync.RWMutex),

		codec:          codec,
		defaultHandler: &regMethod{value, value.Type().In(1)},

		reqMu:   new(sync.Mutex),
		replyMu: new(sync.Mutex),

		Requests: new(sync.WaitGroup),
		clients:  new(int64),
	}

	return s
}
1135139
func NewServer(addr string) (*Server, error) {
	if (Conf == Config{}) {
		InitConf("")
	}

	s := Server{neptulon: neptulon.NewServer(addr)}

	if err := s.SetDB(inmem.NewDB()); err != nil {
		return nil, err
	}
	if err := s.SetQueue(inmem.NewQueue(s.neptulon.SendRequest)); err != nil {
		return nil, err
	}

	s.neptulon.MiddlewareFunc(middleware.Logger)
	s.pubRouter = middleware.NewRouter()
	s.neptulon.Middleware(s.pubRouter)
	initPubRoutes(s.pubRouter, &s.db, Conf.App.JWTPass())

	//all communication below this point is authenticated
	s.neptulon.MiddlewareFunc(jwt.HMAC(Conf.App.JWTPass()))
	s.neptulon.Middleware(s.queue)
	s.privRouter = middleware.NewRouter()
	s.neptulon.Middleware(s.privRouter)
	initPrivRoutes(s.privRouter, &s.queue)
	// todo: r.Middleware(NotFoundHandler()) - 404-like handler, if any request reaches this point without being handled

	s.neptulon.DisconnHandler(func(c *neptulon.Conn) {
		// only handle this event for previously authenticated
		if id, ok := c.Session.GetOk("userid"); ok {
			s.queue.RemoveConn(id.(string))
		}
	})

	return &s, nil
}
540923
func NewServer(id, serverType string, frontend bool, metadata ...map[string]string) *Server {
	d := make(map[string]string)
	h, err := os.Hostname()
	if err != nil {
		logger.Log.Errorf("failed to get hostname: %s", err.Error())
	}
	if len(metadata) > 0 {
		d = metadata[0]
	}
	return &Server{
		ID:       id,
		Type:     serverType,
		Metadata: d,
		Frontend: frontend,
		Hostname: h,
	}
}
308292
func NewServer() *Server {
	return &Server{
		codecs:   make(map[string]Codec),
		services: new(serviceMap),
	}
}
550729
func NewServer(addr string, group []*SiteConfig) (*Server, error) {
	s := &Server{
		Server:      makeHTTPServerWithTimeouts(addr, group),
		vhosts:      newVHostTrie(),
		sites:       group,
		connTimeout: GracefulTimeout,
	}
	s.vhosts.fallbackHosts = append(s.vhosts.fallbackHosts, getFallbacks(group)...)
	s.Server = makeHTTPServerWithHeaderLimit(s.Server, group)
	s.Server.Handler = s // this is weird, but whatever

	// extract TLS settings from each site config to build
	// a tls.Config, which will not be nil if TLS is enabled
	tlsConfig, err := makeTLSConfig(group)
	if err != nil {
		return nil, err
	}
	s.Server.TLSConfig = tlsConfig

	// if TLS is enabled, make sure we prepare the Server accordingly
	if s.Server.TLSConfig != nil {
		// enable QUIC if desired (requires HTTP/2)
		if HTTP2 && QUIC {
			s.quicServer = &h2quic.Server{Server: s.Server}
			s.Server.Handler = s.wrapWithSvcHeaders(s.Server.Handler)
		}

		// wrap the HTTP handler with a handler that does MITM detection
		tlsh := &tlsHandler{next: s.Server.Handler}
		s.Server.Handler = tlsh // this needs to be the "outer" handler when Serve() is called, for type assertion

		// when Serve() creates the TLS listener later, that listener should
		// be adding a reference the ClientHello info to a map; this callback
		// will be sure to clear out that entry when the connection closes.
		s.Server.ConnState = func(c net.Conn, cs http.ConnState) {
			// when a connection closes or is hijacked, delete its entry
			// in the map, because we are done with it.
			if tlsh.listener != nil {
				if cs == http.StateHijacked || cs == http.StateClosed {
					tlsh.listener.helloInfosMu.Lock()
					delete(tlsh.listener.helloInfos, c.RemoteAddr().String())
					tlsh.listener.helloInfosMu.Unlock()
				}
			}
		}

		// As of Go 1.7, if the Server's TLSConfig is not nil, HTTP/2 is enabled only
		// if TLSConfig.NextProtos includes the string "h2"
		if HTTP2 && len(s.Server.TLSConfig.NextProtos) == 0 {
			// some experimenting shows that this NextProtos must have at least
			// one value that overlaps with the NextProtos of any other tls.Config
			// that is returned from GetConfigForClient; if there is no overlap,
			// the connection will fail (as of Go 1.8, Feb. 2017).
			s.Server.TLSConfig.NextProtos = defaultALPN
		}
	}

	// Compile custom middleware for every site (enables virtual hosting)
	for _, site := range group {
		stack := Handler(staticfiles.FileServer{Root: http.Dir(site.Root), Hide: site.HiddenFiles, IndexPages: site.IndexPages})
		for i := len(site.middleware) - 1; i >= 0; i-- {
			stack = site.middleware[i](stack)
		}
		site.middlewareChain = stack
		s.vhosts.Insert(site.Addr.VHost(), site)
	}

	return s, nil
}
1331704
func NewServer(bindHost string, bindPort int, syslogishServer *syslogish.Server) (*Server, error) {
	return &Server{
		bindHost: bindHost,
		bindPort: bindPort,
		handler:  &requestHandler{syslogishServer: syslogishServer},
	}, nil
}
295336
func NewServer(apiDef *raml.APIDefinition, packageName, apiDocsDir, rootImportPath string,
	withMain bool, targetDir string, libsRootURLs []string) *Server {
	// global variables
	rootImportPath = setRootImportPath(rootImportPath, targetDir)
	globAPIDef = apiDef
	globRootImportPath = rootImportPath
	globLibRootURLs = libsRootURLs

	return &Server{
		apiDef:         apiDef,
		PackageName:    packageName,
		apiDocsDir:     apiDocsDir,
		withMain:       withMain,
		RootImportPath: rootImportPath,
		TargetDir:      targetDir,
		libsRootURLs:   libsRootURLs,
	}
}
362442
func (s *Service) NewServer() *Server {
	s.RegisterSDK(Map)

	mux := s.ServeMux
	vim := Map.Path + "/vimService"
	s.sdk[vim] = s.sdk[vim25.Path]
	mux.HandleFunc(vim, s.ServeSDK)
	mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions)
	mux.HandleFunc(folderPrefix, s.ServeDatastore)
	mux.HandleFunc(nfcPrefix, ServeNFC)
	mux.HandleFunc("/about", s.About)

	ts := internal.NewUnstartedServer(mux, s.Listen)
	addr := ts.Listener.Addr().(*net.TCPAddr)
	port := strconv.Itoa(addr.Port)
	u := &url.URL{
		Scheme: "http",
		Host:   net.JoinHostPort(defaultIP(addr), port),
		Path:   Map.Path,
	}
	if s.TLS != nil {
		u.Scheme += "s"
	}

	// Redirect clients to this http server, rather than HostSystem.Name
	Map.SessionManager().ServiceHostName = u.Host

	// Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example)
	m := Map.OptionManager()
	m.Setting = append(m.Setting,
		&types.OptionValue{
			Key:   "vcsim.server.url",
			Value: u.String(),
		},
	)

	u.User = url.UserPassword("user", "pass")

	if s.TLS != nil {
		ts.TLS = s.TLS
		ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate
		Map.SessionManager().TLSCert = func() string {
			return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0])
		}
		ts.StartTLS()
	} else {
		ts.Start()
	}

	return &Server{
		Server: ts,
		URL:    u,
	}
}
162286
func NewServer() *Server {
	s := &Server{
		Router: newRouter(),
		Addr:   "",
		TLS:    nil,
	}

	s.ErrorHandler = StdErrorHandler

	return s
}