當前位置: 首頁>>代碼示例>>Golang>>正文


Golang rata.NewRouter函數代碼示例

本文整理匯總了Golang中github.com/tedsuo/rata.NewRouter函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewRouter函數的具體用法?Golang NewRouter怎麽用?Golang NewRouter使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewRouter函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: newServer

func newServer(args []string) (*http.Server, error) {

	c, err := NewCollector(args[0])
	if err != nil {
		fmt.Errorf("Error creating test collector: %s\n", err)
		return nil, err
	}
	log.Printf("Watching reports dir [%s]\n", c.ReportsDir)

	routes := rata.Routes{
		{Name: "get_index", Method: "GET", Path: "/"},
		{Name: "get_tests", Method: "GET", Path: "/tests"},
	}

	handlers := map[string]http.Handler{
		"get_index": http.FileServer(http.Dir(viewsDir)),
		"get_tests": newTestsHandler(c),
	}

	router, err := rata.NewRouter(routes, handlers)
	if err != nil {
		return nil, err
	}

	server := &http.Server{
		Addr:           ":8080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	return server, nil
}
開發者ID:markstgodard,項目名稱:gawker,代碼行數:33,代碼來源:main.go

示例2: New

func New(logger logger.Logger, store store.Store, clock clock.Clock) (http.Handler, error) {
	handlers := map[string]http.Handler{
		"bulk_app_state": NewBulkAppStateHandler(logger, store, clock),
	}

	return rata.NewRouter(apiserver.Routes, handlers)
}
開發者ID:nagyistge,項目名稱:hm9000,代碼行數:7,代碼來源:handler.go

示例3: constructApiServer

func constructApiServer(cfg config.Config, database db.DB, statsdClient statsd.Statter, stopChan chan struct{}, logger lager.Logger) ifrit.Runner {
	var token authentication.Token

	if *devMode {
		token = authentication.NullToken{}
	} else {
		token = authentication.NewAccessToken(cfg.UAAPublicKey)
		err := token.CheckPublicToken()
		if err != nil {
			logger.Error("failed to check public token", err)
			os.Exit(1)
		}
	}

	validator := handlers.NewValidator()
	routesHandler := handlers.NewRoutesHandler(token, *maxTTL, validator, database, logger)
	eventStreamHandler := handlers.NewEventStreamHandler(token, database, logger, statsdClient, stopChan)

	actions := rata.Handlers{
		"Upsert":      route(routesHandler.Upsert),
		"Delete":      route(routesHandler.Delete),
		"List":        route(routesHandler.List),
		"EventStream": route(eventStreamHandler.EventStream),
	}

	handler, err := rata.NewRouter(routing_api.Routes, actions)
	if err != nil {
		logger.Error("failed to create router", err)
		os.Exit(1)
	}

	handler = handlers.LogWrap(handler, logger)
	return http_server.New(":"+strconv.Itoa(*port), handler)
}
開發者ID:markstgodard,項目名稱:routing-api-cli,代碼行數:34,代碼來源:main.go

示例4: New

func New(logger logger.Logger, store store.Store, timeProvider timeprovider.TimeProvider) (http.Handler, error) {
	handlers := map[string]http.Handler{
		"bulk_app_state": NewBulkAppStateHandler(logger, store, timeProvider),
	}

	return rata.NewRouter(apiserver.Routes, handlers)
}
開發者ID:cgrotz,項目名稱:hm9000,代碼行數:7,代碼來源:handler.go

示例5: initializeServer

func initializeServer(
	bbsClient bbs.Client,
	executorClient executor.Client,
	evacuatable evacuation_context.Evacuatable,
	evacuationReporter evacuation_context.EvacuationReporter,
	logger lager.Logger,
	stackMap rep.StackPathMap,
	supportedProviders []string,
) (ifrit.Runner, string) {
	lrpStopper := initializeLRPStopper(*cellID, executorClient, logger)

	auctionCellRep := auction_cell_rep.New(*cellID, stackMap, supportedProviders, *zone, generateGuid, executorClient, evacuationReporter, logger)
	handlers := handlers.New(auctionCellRep, lrpStopper, executorClient, evacuatable, logger)

	router, err := rata.NewRouter(rep.Routes, handlers)
	if err != nil {
		logger.Fatal("failed-to-construct-router", err)
	}

	ip, err := localip.LocalIP()
	if err != nil {
		logger.Fatal("failed-to-fetch-ip", err)
	}

	port := strings.Split(*listenAddr, ":")[1]
	address := fmt.Sprintf("http://%s:%s", ip, port)

	return http_server.New(*listenAddr, router), address
}
開發者ID:stefanschneider,項目名稱:rep,代碼行數:29,代碼來源:main.go

示例6: SpinUp

func (f *FakeCell) SpinUp(serviceClient bbs.ServiceClient) {
	//make a test-friendly AuctionRepDelegate using the auction package's SimulationRepDelegate
	f.SimulationRep = simulationrep.New(f.stack, "Z0", rep.Resources{
		DiskMB:     100,
		MemoryMB:   100,
		Containers: 100,
	})

	//spin up an http auction server
	logger := lager.NewLogger(f.cellID)
	logger.RegisterSink(lager.NewWriterSink(GinkgoWriter, lager.INFO))

	fakeLRPStopper := new(fake_lrp_stopper.FakeLRPStopper)
	fakeExecutorClient := new(executorfakes.FakeClient)
	fakeEvacuatable := new(fake_evacuation_context.FakeEvacuatable)

	handlers := rephandlers.New(f.SimulationRep, fakeLRPStopper, fakeExecutorClient, fakeEvacuatable, logger)
	router, err := rata.NewRouter(rep.Routes, handlers)
	Expect(err).NotTo(HaveOccurred())
	f.server = httptest.NewServer(router)

	presence := models.NewCellPresence(
		f.cellID,
		f.server.URL,
		"az1",
		models.NewCellCapacity(512, 1024, 124),
		[]string{},
		[]string{})

	f.heartbeater = ifrit.Invoke(serviceClient.NewCellPresenceRunner(logger, &presence, time.Second))
}
開發者ID:emc-xchallenge,項目名稱:auctioneer,代碼行數:31,代碼來源:fake_cell_test.go

示例7: New

func New(bbs bbs.Client, receptorBBS legacybbs.ReceptorBBS, logger lager.Logger, username, password string, corsEnabled bool) http.Handler {
	taskHandler := NewTaskHandler(bbs, logger)
	desiredLRPHandler := NewDesiredLRPHandler(bbs, receptorBBS, logger)
	actualLRPHandler := NewActualLRPHandler(bbs, receptorBBS, logger)
	cellHandler := NewCellHandler(receptorBBS, logger)
	domainHandler := NewDomainHandler(bbs, receptorBBS, logger)
	eventStreamHandler := NewEventStreamHandler(bbs, logger)
	authCookieHandler := NewAuthCookieHandler(logger)

	actions := rata.Handlers{
		// Tasks
		receptor.CreateTaskRoute: route(taskHandler.Create),
		receptor.TasksRoute:      route(taskHandler.GetAll),
		receptor.GetTaskRoute:    route(taskHandler.GetByGuid),
		receptor.DeleteTaskRoute: route(taskHandler.Delete),
		receptor.CancelTaskRoute: route(taskHandler.Cancel),

		// DesiredLRPs
		receptor.CreateDesiredLRPRoute: route(desiredLRPHandler.Create),
		receptor.GetDesiredLRPRoute:    route(desiredLRPHandler.Get),
		receptor.UpdateDesiredLRPRoute: route(desiredLRPHandler.Update),
		receptor.DeleteDesiredLRPRoute: route(desiredLRPHandler.Delete),
		receptor.DesiredLRPsRoute:      route(desiredLRPHandler.GetAll),

		// ActualLRPs
		receptor.ActualLRPsRoute:                         route(actualLRPHandler.GetAll),
		receptor.ActualLRPsByProcessGuidRoute:            route(actualLRPHandler.GetAllByProcessGuid),
		receptor.ActualLRPByProcessGuidAndIndexRoute:     route(actualLRPHandler.GetByProcessGuidAndIndex),
		receptor.KillActualLRPByProcessGuidAndIndexRoute: route(actualLRPHandler.KillByProcessGuidAndIndex),

		// Cells
		receptor.CellsRoute: route(cellHandler.GetAll),

		// Domains
		receptor.UpsertDomainRoute: route(domainHandler.Upsert),
		receptor.DomainsRoute:      route(domainHandler.GetAll),

		// Event Streaming
		receptor.EventStream: route(eventStreamHandler.EventStream),

		// Authentication Cookie
		receptor.GenerateCookie: route(authCookieHandler.GenerateCookie),
	}

	handler, err := rata.NewRouter(receptor.Routes, actions)
	if err != nil {
		panic("unable to create router: " + err.Error())
	}

	if username != "" {
		handler = CookieAuthWrap(BasicAuthWrap(handler, username, password), receptor.AuthorizationCookieName)
	}

	if corsEnabled {
		handler = CORSWrapper(handler)
	}

	return LogWrap(handler, logger)
}
開發者ID:davidwadden,項目名稱:lattice-release,代碼行數:59,代碼來源:handlers.go

示例8: New

func New(staticDirectory string, logger lager.Logger) (http.Handler, error) {
	staticRoute, err := fileserver.Routes.CreatePathForRoute(fileserver.StaticRoute, nil)
	if err != nil {
		return nil, err
	}

	return rata.NewRouter(fileserver.Routes, rata.Handlers{
		fileserver.StaticRoute: static.New(staticDirectory, staticRoute, logger),
	})
}
開發者ID:emc-xchallenge,項目名稱:file-server,代碼行數:10,代碼來源:handlers.go

示例9: NewHandler

func NewHandler(logger lager.Logger, client volman.Manager) (http.Handler, error) {
	logger = logger.Session("server")
	logger.Info("start")
	defer logger.Info("end")

	var handlers = rata.Handlers{
		"drivers": newListDriversHandler(logger, client),
		"mount":   newMountHandler(logger, client),
		"unmount": newUnmountHandler(logger, client),
	}

	return rata.NewRouter(volman.Routes, handlers)
}
開發者ID:cloudfoundry-incubator,項目名稱:volman,代碼行數:13,代碼來源:handlers.go

示例10: main

func main() {
	flag.Parse()

	logger := lager.NewLogger("lattice-app")
	if quiet {
		logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.INFO))
	} else {
		logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))
	}

	ports := getServerPorts()

	logger.Info("lattice-app.starting", lager.Data{"ports": ports})
	handler, err := rata.NewRouter(routes.Routes, handlers.New(logger))
	if err != nil {
		logger.Fatal("router.creation.failed", err)
	}

	index, err := helpers.FetchIndex()
	appName := fetchAppName()
	go func() {
		t := time.NewTicker(time.Second)
		for {
			<-t.C
			if err != nil {
				fmt.Fprintf(os.Stderr, "Failed to fetch index: %s\n", err.Error())
			} else {
				fmt.Println(fmt.Sprintf("%s. Says %s. on index: %d", appName, message, index))
			}
		}
	}()

	wg := sync.WaitGroup{}
	for _, port := range ports {
		wg.Add(1)
		go func(wg *sync.WaitGroup, port string) {
			defer wg.Done()
			server := ifrit.Envoke(http_server.New(":"+port, handler))
			logger.Info("lattice-app.up", lager.Data{"port": port})
			err = <-server.Wait()
			if err != nil {
				logger.Error("shutting down server", err, lager.Data{"server port": port})
			}
			logger.Info("shutting down server", lager.Data{"server port": port})
		}(&wg, port)
	}
	wg.Wait()
	logger.Info("shutting latice app")
}
開發者ID:predix,項目名稱:lattice-app,代碼行數:49,代碼來源:main.go

示例11: New

func New(runner auctiontypes.AuctionRunner, logger lager.Logger) http.Handler {
	taskAuctionHandler := logWrap(route(NewTaskAuctionHandler(runner).Create), logger)
	lrpAuctionHandler := logWrap(route(NewLRPAuctionHandler(runner).Create), logger)

	actions := rata.Handlers{
		CreateTaskAuctionsRoute: taskAuctionHandler,
		CreateLRPAuctionsRoute:  lrpAuctionHandler,
	}

	handler, err := rata.NewRouter(Routes, actions)
	if err != nil {
		panic("unable to create router: " + err.Error())
	}

	return handler
}
開發者ID:Gerg,項目名稱:bbs,代碼行數:16,代碼來源:handlers.go

示例12: constructApiServer

func constructApiServer(cfg config.Config, database db.DB, statsdClient statsd.Statter, stopChan chan struct{}, logger lager.Logger) ifrit.Runner {
	var tokenValidator authentication.TokenValidator

	if *devMode {
		tokenValidator = authentication.NullTokenValidator{}
	} else {
		uaaKeyFetcher := authentication.NewUaaKeyFetcher(logger, cfg.UAAEndpoint+"/token_key")
		uaaPublicKey, err := uaaKeyFetcher.FetchKey()
		if err != nil {
			logger.Error("Failed to get verification key from UAA", err)
			os.Exit(1)
		}
		tokenValidator = authentication.NewAccessTokenValidator(logger, uaaPublicKey, uaaKeyFetcher)
		err = tokenValidator.CheckPublicToken()
		if err != nil {
			logger.Error("Failed to check public token", err)
			os.Exit(1)
		}
	}

	validator := handlers.NewValidator()
	routesHandler := handlers.NewRoutesHandler(tokenValidator, *maxTTL, validator, database, logger)
	eventStreamHandler := handlers.NewEventStreamHandler(tokenValidator, database, logger, statsdClient, stopChan)
	routeGroupsHandler := handlers.NewRouteGroupsHandler(tokenValidator, logger)
	tcpMappingsHandler := handlers.NewTcpRouteMappingsHandler(tokenValidator, validator, database, logger)

	actions := rata.Handlers{
		routing_api.UpsertRoute:           route(routesHandler.Upsert),
		routing_api.DeleteRoute:           route(routesHandler.Delete),
		routing_api.ListRoute:             route(routesHandler.List),
		routing_api.EventStreamRoute:      route(eventStreamHandler.EventStream),
		routing_api.ListRouterGroups:      route(routeGroupsHandler.ListRouterGroups),
		routing_api.UpsertTcpRouteMapping: route(tcpMappingsHandler.Upsert),
		routing_api.DeleteTcpRouteMapping: route(tcpMappingsHandler.Delete),
		routing_api.ListTcpRouteMapping:   route(tcpMappingsHandler.List),
		routing_api.EventStreamTcpRoute:   route(eventStreamHandler.TcpEventStream),
	}

	handler, err := rata.NewRouter(routing_api.Routes, actions)
	if err != nil {
		logger.Error("failed to create router", err)
		os.Exit(1)
	}

	handler = handlers.LogWrap(handler, logger)
	return http_server.New(":"+strconv.Itoa(int(*port)), handler)
}
開發者ID:shashankmjain,項目名稱:gorouter,代碼行數:47,代碼來源:main.go

示例13: rataWrap

func rataWrap(handler http.Handler, method, path string, params rata.Params) (http.Handler, *http.Request) {
	testRoutes := rata.Routes{
		{Name: "wicked_smat", Method: method, Path: path},
	}
	requestGenerator := rata.NewRequestGenerator("", testRoutes)
	testHandlers := rata.Handlers{
		"wicked_smat": handler,
	}

	router, err := rata.NewRouter(testRoutes, testHandlers)
	Expect(err).NotTo(HaveOccurred())

	request, err := requestGenerator.CreateRequest("wicked_smat", params, nil)
	Expect(err).NotTo(HaveOccurred())

	return router, request
}
開發者ID:cloudfoundry-incubator,項目名稱:ducati-daemon,代碼行數:17,代碼來源:handlers_suite_test.go

示例14: New

func New(enqueue chan<- models.Task, logger lager.Logger) http.Handler {
	taskHandler := NewHandler(enqueue, logger)

	actions := rata.Handlers{
		// internal Tasks
		routes.CompleteTasks: taskHandler,
	}

	handler, err := rata.NewRouter(routes.CompleteTasksRoutes, actions)
	if err != nil {
		panic("unable to create router: " + err.Error())
	}

	handler = handlers.LogWrap(handler, logger)

	return handler
}
開發者ID:rajkumargithub,項目名稱:lattice,代碼行數:17,代碼來源:handlers.go

示例15: NewServer

func NewServer(secret string, enqueuer *build.Enqueuer) http.Handler {
	cbHandler := &callbackHandler{
		enqueuer: enqueuer,
	}

	handlers := map[string]http.Handler{
		Callback: GitHubHMAC(secret, http.HandlerFunc(cbHandler.callback)),
	}

	router, err := rata.NewRouter(Routes, handlers)
	if err != nil {
		panic(err)
	}

	return &server{
		rootHandler: router,
	}
}
開發者ID:xoebus,項目名稱:checkin,代碼行數:18,代碼來源:server.go


注:本文中的github.com/tedsuo/rata.NewRouter函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。