当前位置: 首页>>代码示例>>Golang>>正文


Golang http.NewServeMux函数代码示例

本文整理汇总了Golang中net/http.NewServeMux函数的典型用法代码示例。如果您正苦于以下问题:Golang NewServeMux函数的具体用法?Golang NewServeMux怎么用?Golang NewServeMux使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewServeMux函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: init

// launch unix and tcp servers
func init() {
	mux := http.NewServeMux()
	rpcserver.RegisterRPCFuncs(mux, Routes)
	wm := rpcserver.NewWebsocketManager(Routes, nil)
	mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
	go func() {
		_, err := rpcserver.StartHTTPServer(tcpAddr, mux)
		if err != nil {
			panic(err)
		}
	}()

	mux2 := http.NewServeMux()
	rpcserver.RegisterRPCFuncs(mux2, Routes)
	wm = rpcserver.NewWebsocketManager(Routes, nil)
	mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
	go func() {
		_, err := rpcserver.StartHTTPServer(unixAddr, mux2)
		if err != nil {
			panic(err)
		}
	}()

	// wait for servers to start
	time.Sleep(time.Second * 2)

}
开发者ID:tendermint,项目名称:go-rpc,代码行数:28,代码来源:rpc_test.go

示例2: Load

// Load
func (p *Application) Load(fn ActionLoadFunc) {
	// hosts
	for _, m := range p.Hosts {
		if _, ok := muxList[m.Listen]; !ok {
			muxList[m.Listen] = http.NewServeMux()
		}

		if m.Path == "/" {
			muxList[m.Listen].Handle(m.Path, http.FileServer(http.Dir(m.Root)))
		} else {
			// To serve a directory on disk (/tmp) under an alternate URL
			// path (/tmpfiles/), use StripPrefix to modify the request
			// URL's path before the FileServer sees it:
			muxList[m.Listen].Handle(m.Path, http.StripPrefix(m.Path, http.FileServer(http.Dir(m.Root))))
		}
	}

	// modules
	for mName, m := range p.Modules {
		if _, ok := muxList[m.Listen]; !ok {
			muxList[m.Listen] = http.NewServeMux()
		}

		muxList[m.Listen].HandleFunc("/"+mName+"/", NewHandler(fn))
	}
}
开发者ID:anycak,项目名称:web,代码行数:27,代码来源:application.go

示例3: main

func main() {
	cfg := new(Config)
	flagx.Parse(cfg)

	InitMongo(cfg.Mongo, cfg.Db)
	mux := http.NewServeMux()
	Handler(mux)
	if cfg.Key != "" {
		done := make(chan bool)
		go func() {
			err := http.ListenAndServeTLS(":443", cfg.Crt, cfg.Key, mux)
			if err != nil {
				logex.Error(err)
			}
			done <- err == nil
		}()
		d := true
		select {
		case <-time.After(time.Second):
		case d = <-done:
		}
		if d {
			mux := http.NewServeMux()
			RedirectHandler(mux)
			if err := http.ListenAndServe(cfg.Listen, mux); err != nil {
				logex.Error(err)
			}
			return
		}
	}
	if err := http.ListenAndServe(cfg.Listen, mux); err != nil {
		logex.Error(err)
	}
}
开发者ID:chzyer,项目名称:pocket,代码行数:34,代码来源:pocket.go

示例4: TestIntegSingle

func TestIntegSingle(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
	srvr := httptest.NewServer(mux)

	u, err := url.Parse(srvr.URL)
	if err != nil {
		t.Fatal(err)
	}

	urls := []*url.URL{u}
	rule := &porter.Rule{"127.0.0.1", urls}

	p, err := porter.New([]*porter.Rule{rule})
	if err != nil {
		t.Fatal(err)
	}

	pMux := http.NewServeMux()
	pMux.Handle("/", p)
	pSrvr := httptest.NewServer(pMux)

	res, err := http.Get(pSrvr.URL + "/")
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()

	want := http.StatusOK
	got := res.StatusCode
	if want != got {
		t.Fatalf("want %d, got %d", want, got)
	}
}
开发者ID:codemodus,项目名称:porter,代码行数:34,代码来源:porter_integ_test.go

示例5: TestInstallSwaggerAPI

// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	etcdserver, _, assert := setUp(t)
	defer etcdserver.Terminate(t)

	mux := http.NewServeMux()
	server := &GenericAPIServer{}
	server.HandlerContainer = NewHandlerContainer(mux, nil)

	// Ensure swagger isn't installed without the call
	ws := server.HandlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	server.InstallSwaggerAPI()
	ws = server.HandlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	server.HandlerContainer = NewHandlerContainer(mux, nil)
	server.ExternalAddress = ""
	server.ClusterIP = net.IPv4(10, 10, 10, 10)
	server.PublicReadWritePort = 1010
	server.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
开发者ID:bryk,项目名称:kubernetes,代码行数:36,代码来源:genericapiserver_test.go

示例6: startPod

func (s *TestHttpService) startPod() error {
	unsecurePodServer := http.NewServeMux()
	unsecurePodServer.HandleFunc("/", s.handleHelloPod)
	unsecurePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPodTest)
	unsecurePodServer.Handle("/"+s.PodWebSocketPath, websocket.Handler(s.handleWebSocket))

	if err := s.startServing(s.PodHttpAddr, unsecurePodServer); err != nil {
		return err
	}

	alternatePodServer := http.NewServeMux()
	alternatePodServer.HandleFunc("/", s.handleHelloPod2)
	alternatePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPod2)

	if err := s.startServing(s.AlternatePodHttpAddr, alternatePodServer); err != nil {
		return err
	}

	securePodServer := http.NewServeMux()
	securePodServer.HandleFunc("/", s.handleHelloPodSecure)
	securePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPodTestSecure)
	securePodServer.Handle("/"+s.PodWebSocketPath, websocket.Handler(s.handleWebSocket))
	if err := s.startServingTLS(s.PodHttpsAddr, s.PodHttpsCert, s.PodHttpsKey, s.PodHttpsCaCert, securePodServer); err != nil {
		return err
	}

	return nil
}
开发者ID:asiainfoLDP,项目名称:datafactory,代码行数:28,代码来源:router_http_server.go

示例7: main

func main() {
	// config parsing
	flag.Parse()
	err := parseConfigFile()
	if err != nil {
		l.Fatal(err)
	}

	// log configuration
	w, err := getLogWriter()
	if err != nil {
		l.Fatal(err)
	}
	defer (*w).Close()

	l = log.New(w, "", log.LstdFlags|log.Lshortfile)

	go handleSignals()
	go EventSourceClientQueryProcess()

	publicMux := http.NewServeMux()
	publicMux.HandleFunc("/", eventSourceHandler)
	go http.ListenAndServe(config.ListenPublic, publicMux)

	internalMux := http.NewServeMux()
	internalMux.HandleFunc("/message", internalHandler)
	l.Fatal(http.ListenAndServe(config.ListenInternal, internalMux))

}
开发者ID:tomeslav,项目名称:locallysourced,代码行数:29,代码来源:locallysourced.go

示例8: TestDispatchFailed

func TestDispatchFailed(t *testing.T) {
	muxV1 := http.NewServeMux()
	muxV2 := http.NewServeMux()

	apiV1 := NewVersion("v1", muxV1)
	apiV2 := NewVersion("v2", muxV2)

	vendor, err := NewVendorMiddleware("mybusiness.com", apiV1, apiV2)
	if err != nil {
		t.Error("Unexpected error:", err)
		t.Fail()
	}

	_, err = vendor.version("v1")

	if err != nil {
		t.Error("Unexpected error:", err)
		t.Fail()
	}

	_, err = vendor.version("v2")

	if err != nil {
		t.Error("Unexpected error:", err)
		t.Fail()
	}

	_, err = vendor.version("v99")

	if err != ErrVersionNotFound {
		t.Error("Expected a not found error:", err)
		t.Fail()
	}
}
开发者ID:yageek,项目名称:apiversion,代码行数:34,代码来源:vendor_test.go

示例9: StartServer

func (h WebserviceHandler) StartServer() {
	commonHandlers := alice.New(context.ClearHandler, h.LoggingHandler, h.RecoverHandler, h.NoCacheHandler)
	authHandlers := commonHandlers.Append(h.AuthHandler)
	h.mrouter = NewRouter()
	h.frouter = http.NewServeMux()
	h.frouter.Handle("/", http.FileServer(http.Dir(h.config.GetHTTPDir())))

	h.mrouter.Get("/item.html", authHandlers.ThenFunc(h.ItemHTML))
	h.mrouter.Get("/services/items", commonHandlers.ThenFunc(h.GetItems))
	h.mrouter.Get("/services/bestComments", commonHandlers.Append(h.GzipJsonHandler).ThenFunc(h.GetBestComments))
	h.mrouter.Post("/services/register", commonHandlers.ThenFunc(h.Register))
	h.mrouter.Post("/services/login", commonHandlers.ThenFunc(h.Login))
	h.mrouter.Get("/services/confirm", commonHandlers.ThenFunc(h.ConfirmEmail))
	h.mrouter.Get("/services/itemInfo", commonHandlers.Append(h.GzipJsonHandler).ThenFunc(h.GetItemInfo))
	h.mrouter.Get("/services/logout", authHandlers.ThenFunc(h.Logout))
	h.mrouter.Get("/services/like", authHandlers.ThenFunc(h.PostLike))
	h.mrouter.Post("/services/comment", authHandlers.ThenFunc(h.PostComment))
	h.mrouter.Get("/services/deletecomment", authHandlers.ThenFunc(h.DeleteComment))
	h.mrouter.Post("/services/deployFront", commonHandlers.Append(h.BasicAuth).ThenFunc(h.DeployFront))

	var err error

	r := http.NewServeMux()
	r.HandleFunc("/", h.FrontHandler)
	go func() {
		log.Infof("Server launched on port %s", h.config.GetServerPort())
		err = http.ListenAndServe(":"+h.config.GetServerPort(), r)
		if err != nil {
			panic(err.Error())
		}
	}()

}
开发者ID:beppeben,项目名称:m3m3,代码行数:33,代码来源:web.go

示例10: TestInstallSwaggerAPI

// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	master, _, assert := setUp(t)
	mux := http.NewServeMux()
	master.handlerContainer = NewHandlerContainer(mux)

	// Ensure swagger isn't installed without the call
	ws := master.handlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	master.InstallSwaggerAPI()
	ws = master.handlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	master.handlerContainer = NewHandlerContainer(mux)
	master.externalHost = ""
	master.clusterIP = net.IPv4(10, 10, 10, 10)
	master.publicReadWritePort = 1010
	master.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
开发者ID:jas1994,项目名称:kubernetes,代码行数:33,代码来源:master_test.go

示例11: StartHTTP

// StartHTTP start listen http.
func StartHTTP() {
	// external
	httpServeMux := http.NewServeMux()
	// 2
	httpServeMux.HandleFunc("/2/server/get", GetServer2)
	// 1.0
	httpServeMux.HandleFunc("/1/server/get", GetServer)
	httpServeMux.HandleFunc("/1/msg/get", GetOfflineMsg)
	httpServeMux.HandleFunc("/1/time/get", GetTime)
	// old
	httpServeMux.HandleFunc("/server/get", GetServer0)
	httpServeMux.HandleFunc("/msg/get", GetOfflineMsg0)
	httpServeMux.HandleFunc("/time/get", GetTime0)
	// internal
	httpAdminServeMux := http.NewServeMux()
	// 1.0
	httpAdminServeMux.HandleFunc("/1/admin/push/private", PushPrivate)
	httpAdminServeMux.HandleFunc("/1/admin/push/mprivate", PushMultiPrivate)
	httpAdminServeMux.HandleFunc("/1/admin/msg/del", DelPrivate)
	// old
	httpAdminServeMux.HandleFunc("/admin/push", PushPrivate)
	httpAdminServeMux.HandleFunc("/admin/msg/clean", DelPrivate)
	for _, bind := range Conf.HttpBind {
		log.Info("start http listen addr:\"%s\"", bind)
		go httpListen(httpServeMux, bind)
	}
	for _, bind := range Conf.AdminBind {
		log.Info("start admin http listen addr:\"%s\"", bind)
		go httpListen(httpAdminServeMux, bind)
	}
}
开发者ID:Terry-Mao,项目名称:gopush-cluster,代码行数:32,代码来源:http.go

示例12: getMux

func (s *apiSvc) getMux() *http.ServeMux {
	mux := http.NewServeMux()

	getApiMux := http.NewServeMux()
	getApiMux.HandleFunc("/api/system/config", s.getSystemConfig)
	getApiMux.HandleFunc("/api/system/config/insync", s.getSystemConfigInSync)
	getApiMux.HandleFunc("/api/system/connections", s.getSystemConnections)
	getApiMux.HandleFunc("/api/system/pins/status", s.getPinStatus)
	getApiMux.HandleFunc("/api/verify/deviceid", s.getDeviceID) // id
	getApiMux.HandleFunc("/api/db/browse", s.getDBBrowse)       // folderID pathPrefix

	postApiMux := http.NewServeMux()
	postApiMux.HandleFunc("/api/system/config", s.postSystemConfig)       // <body>
	postApiMux.HandleFunc("/api/verify/humansize", s.postVerifyHumanSize) // <body>

	apiMux := getMethodHandler(getApiMux, postApiMux)
	mux.Handle("/api/", apiMux)

	// Serve compiled in assets unless an asset directory was set (for development)
	mux.Handle("/", embeddedStatic{
		assetDir: s.assetDir,
		assets:   autogenerated.Assets(),
	})

	return mux
}
开发者ID:burkemw3,项目名称:syncthingfuse,代码行数:26,代码来源:gui.go

示例13: Start

func Start(config *Config) error {
	if err := clone(config); err != nil {
		return err
	}
	handler := handler(config)

	ops := http.NewServeMux()
	if config.AllowHooks {
		ops.Handle("/hooks/", prometheus.InstrumentHandler("hooks", http.StripPrefix("/hooks", hooksHandler(config))))
	}
	/*ops.Handle("/reflect/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()
		fmt.Fprintf(os.Stdout, "%s %s\n", r.Method, r.URL)
		io.Copy(os.Stdout, r.Body)
	}))*/
	ops.Handle("/metrics", prometheus.UninstrumentedHandler())
	healthz.InstallHandler(ops)

	mux := http.NewServeMux()
	mux.Handle("/", prometheus.InstrumentHandler("git", handler))
	mux.Handle("/_/", http.StripPrefix("/_", ops))

	log.Printf("Serving %s on %s", config.Home, config.Listen)
	return http.ListenAndServe(config.Listen, mux)
}
开发者ID:cjnygard,项目名称:origin,代码行数:25,代码来源:gitserver.go

示例14: TestAddRoute

func TestAddRoute(t *testing.T) {
	m := NewMux("", http.NewServeMux())
	r := m.Add("GET", "products/{action}/{id}", dummy)
	assertEqual(t, r.Method, "GET")
	assertEqual(t, r.Pattern, "products/{action}/{id}")
	assertEqual(t, r.Name, "")
	if r.Handler == nil {
		t.Fatalf("Expected dummy handler, got nil")
	}
	if r.mux != m {
		t.Fatalf("Expected original muxer, got %v", r.mux)
	}

	m2 := NewMux("/api", http.NewServeMux())
	r2 := m2.Add("PUT", "/scores/{id}", dummy)
	assertEqual(t, r2.Method, "PUT")
	assertEqual(t, r2.Pattern, "scores/{id}")

	defer func() {
		if err := recover(); err == nil {
			t.Fatalf("Expected panic, got no error instead")
		}
	}()
	// should panic because of the same method + pattern
	m2.Add("PUT", "/scores/{id}", dummy)
}
开发者ID:crhym3,项目名称:muxer,代码行数:26,代码来源:muxer_test.go

示例15: Start

// Start starts up the server.
func (a *App) Start() {
	a.gamekeeper.init()

	// Load all the html templates
	a.templates = template.Must(template.ParseFiles("static/index.html"))

	// Initialize the websocket upgrader
	a.upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	// Initialize the http servers.
	a.publicServer = http.Server{
		Addr:    publicListenAddress,
		Handler: http.HandlerFunc(a.servePublicHTTP),
	}
	a.internalServer = http.Server{
		Addr:    internalListenAddress,
		Handler: http.HandlerFunc(a.serveInternalHTTP),
	}
	a.publicMux = http.NewServeMux()
	a.internalMux = http.NewServeMux()

	// Setup the routes.
	a.publicMux.HandleFunc("/connect", a.websocketUpgradeRoute)
	a.publicMux.HandleFunc("/time", a.time)
	a.publicMux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
	a.publicMux.HandleFunc("/", a.index)

	go a.listenAndServe(&a.publicServer)
	go a.listenAndServe(&a.internalServer)

	a.stopped.Add(1)
}
开发者ID:jbowens,项目名称:itsawordgame.com,代码行数:36,代码来源:app.go


注:本文中的net/http.NewServeMux函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。