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


Golang httprouter.New函数代码示例

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


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

示例1: main

func main() {

	router1 := httprouter.New()
	router1.GET("/keys", GetKeyServer3000)
	router1.PUT("/keys/:key_id/:value", PutServer1)
	server := http.Server{
		Addr:    "0.0.0.0:3000",
		Handler: router1,
	}
	router2 := httprouter.New()
	router2.GET("/keys", GetKeyServer3001)
	router2.PUT("/keys/:key_id/:value", PutServer2)

	go func() {
		http.ListenAndServe("localhost:3001", router2)
	}()

	router3 := httprouter.New()
	router3.GET("/keys", GetKeyServer3002)
	router3.PUT("/keys/:key_id/:value", PutServer3)

	go func() {
		http.ListenAndServe("localhost:3002", router3)
	}()

	server.ListenAndServe()

}
开发者ID:DeepaDhingra,项目名称:cmpe273-lab3,代码行数:28,代码来源:MainFile.go

示例2: APIHandler

func APIHandler(conf *Config) http.Handler {
	api := &API{
		conf: conf,
	}
	if conf.Cache {
		if err := api.cacheDashboardJS(); err != nil {
			panic(err)
		}
	}

	router := httprouter.New()
	router2 := httprouter.New()

	prefixPath := func(p string) string {
		return path.Join(conf.PathPrefix, p)
	}

	router.HandlerFunc("GET", status.Path, status.HealthyHandler.ServeHTTP)

	router.POST(prefixPath("/user/sessions"), api.WrapHandler(api.Login))
	router.DELETE(prefixPath("/user/session"), api.WrapHandler(api.Logout))

	router.GET(prefixPath("/config"), api.WrapHandler(api.GetConfig))

	router.NotFound = router2.ServeHTTP
	router2.GET(prefixPath("/*path"), api.WrapHandler(api.ServeAsset))

	return httphelper.ContextInjector("dashboard",
		httphelper.NewRequestLogger(
			api.CorsHandler(router)))
}
开发者ID:ably-forks,项目名称:flynn,代码行数:31,代码来源:api.go

示例3: runHTTPListeners

func runHTTPListeners(d db.DB) {
	httpMux := htr.New()
	httpsMux := htr.New()

	// httpMux.SetupRoutes()
	err := api.SetupRoutes(
		httpsMux,
		api.Auth(d),
		api.User(d),
		api.Task(d),
	)

	if err != nil {
		log.Fatalf("router setup failed: %s\n", err.Error())
	}

	var (
		httpErr  = make(chan error)
		httpsErr = make(chan error)
	)

	println("Listening on HTTP 25000")
	println("Listening on HTTPS 25001")

	go func() { httpErr <- http.ListenAndServeTLS(":25001", "cert.pem", "key.key", httpsMux) }()
	go func() { httpsErr <- http.ListenAndServe(":25000", httpMux) }()

	var e error
	select {
	case e = <-httpErr:
	case e = <-httpsErr:
	}
	log.Fatalf("error serving http(s): %s", e.Error())
}
开发者ID:kamaln7,项目名称:mf-proto,代码行数:34,代码来源:main.go

示例4: main

func main() {
	flag.Parse()

	// initialize database
	db, err := bolt.Open(*database, 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		log.Fatalf("Could not open database: %s", err)
	}
	defer db.Close()

	if err := db.Update(initBuckets); err != nil {
		log.Fatal(err)
	}

	hookStore := &HookStore{db}

	// webhooks
	hh := &HookHandler{hookStore, db}
	router := httprouter.New()
	router.GET("/h/:id", hh.ReceiveHook)
	router.POST("/h/:id", hh.ReceiveHook)

	go func() {
		log.Printf("Listening on %s", *listenAddr)
		log.Print(http.ListenAndServe(*listenAddr, router))
	}()

	hooks, err := hookStore.List()
	if err != nil {
		log.Fatal("Fail to load hooks")
	}
	ist := NewIssueStatusTracker(NewIssueAPI(), hooks, db)

	// admin interface
	ah := &AdminHandler{hooks: hookStore, ist: ist}
	arouter := httprouter.New()
	arouter.Handler("GET", "/public/*path", http.StripPrefix("/public", http.FileServer(http.Dir("public"))))
	arouter.GET("/", ah.Index)
	arouter.Handler("GET", "/hooks", http.RedirectHandler("/", http.StatusMovedPermanently))

	arouter.GET("/hooks/new", ah.NewHook)
	arouter.POST("/hooks", ah.CreateHook)
	arouter.GET("/hooks/edit/:id", ah.EditHook)
	arouter.POST("/hooks/edit/:id", ah.UpdateHook)

	arouter.GET("/hooks/edit/:id/add", ah.AddComponent)
	arouter.POST("/hooks/edit/:id/create", ah.CreateComponent)
	arouter.GET("/hooks/edit/:id/edit/:c", ah.EditComponent)
	arouter.POST("/hooks/edit/:id/update/:c", ah.UpdateComponent)

	go func() {
		log.Printf("Admin interface on %s", *adminAddr)
		log.Print(http.ListenAndServe(*adminAddr, arouter))
	}()

	ist.RefreshIssues()
	ist.StartPolling()
}
开发者ID:vampirewalk,项目名称:rehook,代码行数:58,代码来源:main.go

示例5: New

func New(e *engine.Engine) *App {

	if e == nil {
		panic("httphandler.New(e *engine.Engine): e is nil")
	}

	app := &App{
		engine: e,
		mux:    http.NewServeMux(),
	}

	// ---------------------------------------------------------------------------

	var (
		ordersRouter     = httprouter.New()
		orderItemsRouter = httprouter.New()
		productsRouter   = httprouter.New()
	)

	productsRouter.POST("/products/", app.createProductHandler)
	productsRouter.GET("/products/:id", app.loadProductHandler)
	productsRouter.GET("/products/", app.listProductsHandler)
	productsRouter.PUT("/products/:id", app.updateProductHandler)

	ordersRouter.POST("/orders/", app.createOrderHandler)
	ordersRouter.GET("/orders/:id", app.loadOrderHandler)
	ordersRouter.GET("/orders/", app.listOrdersHandler)
	ordersRouter.PUT("/orders/:id", app.updateOrderHandler)

	orderItemsRouter.POST("/orders/:orderID/items/", app.createOrderItemHandler)
	orderItemsRouter.GET("/orders/:orderID/items/:productID", app.loadOrderItemHandler)
	orderItemsRouter.GET("/orders/:orderID/items/", app.listOrderItemsHandler)
	orderItemsRouter.PUT("/orders/:orderID/items/:productID", app.updateOrderItemHandler)
	orderItemsRouter.DELETE("/orders/:orderID/items/:productID", app.removeOrderItemHandler)

	// (facepalm) using httphandler here was not the best decision:
	app.mux.HandleFunc("/orders/", func(w http.ResponseWriter, r *http.Request) {
		if strings.Contains(r.URL.Path, "/items") {
			orderItemsRouter.ServeHTTP(w, r)
		} else {
			ordersRouter.ServeHTTP(w, r)
		}
	})

	app.mux.Handle("/", productsRouter)

	// ---------------------------------------------------------------------------

	return app
}
开发者ID:mxmCherry,项目名称:goshop,代码行数:50,代码来源:app.go

示例6: loadHttpRouter

func loadHttpRouter(routes []route) http.Handler {
	router := httprouter.New()
	for _, route := range routes {
		router.Handle(route.method, route.path, httpRouterHandle)
	}
	return router
}
开发者ID:lamproae,项目名称:go-http-routing-benchmark,代码行数:7,代码来源:routers.go

示例7: main

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/user/*name", Index)

	log.Fatal(http.ListenAndServe(":8080", router))
}
开发者ID:RaviTezu,项目名称:GolangTraining,代码行数:7,代码来源:main.go

示例8: attachRoutes

func (c *context) attachRoutes() {
	c.router = httprouter.New()

	_routes := *c.routes
	for i := range _routes {
		// Individual Controller calls per routes are expected to happen from here
		d := D{c: c, actions: _routes[i].actions, data: make(map[string]interface{})}
		switch _routes[i].method {
		case "GET":
			c.router.GET(_routes[i].url, d.call)
			break
		case "POST":
			c.router.POST(_routes[i].url, d.call)
			break
		case "PUT":
			c.router.PUT(_routes[i].url, d.call)
			break
		case "DELETE":
			c.router.DELETE(_routes[i].url, d.call)
			break
		case "OPTIONS":
			c.router.OPTIONS(_routes[i].url, d.call)
			break
		default:
			break
		}
	}
}
开发者ID:khrm,项目名称:apis.V2,代码行数:28,代码来源:context.go

示例9: main

func main() {
	routes, err := ParseRoutes(".")
	if err != nil {
		log.Fatal(err)
	}
	db, err = GetDbConnection()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	router := httprouter.New()
	for _, route := range routes {
		if route.Method == "GET" {
			router.GET(route.Path, handler(route))
		}
		if route.Method == "POST" {
			router.POST(route.Path, handler(route))
		}
		if route.Method == "PUT" {
			router.PUT(route.Path, handler(route))
		}
		if route.Method == "DELETE" {
			router.DELETE(route.Path, handler(route))
		}
	}
	port := "8080"
	if len(os.Args) > 1 {
		port = os.Args[1]
	}
	log.Fatal(http.ListenAndServe(":"+port, router))
}
开发者ID:lacion,项目名称:dbservice,代码行数:31,代码来源:main.go

示例10: newStatusServer

// newStatusServer allocates and returns a statusServer.
func newStatusServer(
	db *client.DB,
	gossip *gossip.Gossip,
	metricSource metricMarshaler,
	ctx *base.Context,
	rpcCtx *rpc.Context,
	stores *storage.Stores,
) *statusServer {
	server := &statusServer{
		db:           db,
		gossip:       gossip,
		metricSource: metricSource,
		router:       httprouter.New(),
		rpcCtx:       rpcCtx,
		stores:       stores,
	}

	server.router.GET(statusLogFilesListPattern, server.handleLogFilesList)
	server.router.GET(statusLogFilePattern, server.handleLogFile)
	server.router.GET(statusLogsPattern, server.handleLogs)
	// TODO(tschottdorf): significant overlap with /debug/pprof/goroutine,
	// except that this one allows querying by NodeID.
	server.router.GET(statusStacksPattern, server.handleStacks)
	server.router.GET(statusMetricsPattern, server.handleMetrics)
	server.router.GET(statusVars, server.handleVars)

	return server
}
开发者ID:yangxuanjia,项目名称:cockroach,代码行数:29,代码来源:status.go

示例11: setupRoutes

func (this *Monitor) setupRoutes() {
	this.router = httprouter.New()
	this.router.GET("/ver", this.versionHandler)
	this.router.GET("/metrics", this.metricsHandler)
	this.router.PUT("/set", this.configHandler)
	this.router.POST("/alertHook", this.alertHookHandler) // zabbix will call me on alert event
}
开发者ID:funkygao,项目名称:gafka,代码行数:7,代码来源:api.go

示例12: NewAPIWithMarshalers

// NewAPIWithMarshalers does the same as NewAPIWithBaseURL with the addition
// of a set of marshalers that provide a way to interact with clients that
// use a serialization format other than JSON. The marshalers map is indexed
// by the MIME content type to use for a given request-response pair. If the
// client provides an Accept header the server will respond using the client's
// preferred content type, otherwise it will respond using whatever content
// type the client provided in its Content-Type request header.
func NewAPIWithMarshalers(prefix string, baseURL string, marshalers map[string]ContentMarshaler) *API {
	if len(marshalers) == 0 {
		panic("marshaler map must not be empty")
	}

	// Add initial and trailing slash to prefix
	prefixSlashes := strings.Trim(prefix, "/")
	if len(prefixSlashes) > 0 {
		prefixSlashes = "/" + prefixSlashes + "/"
	} else {
		prefixSlashes = "/"
	}

	router := httprouter.New()
	router.MethodNotAllowed = notAllowedHandler{marshalers: marshalers}

	info := information{prefix: prefix, baseURL: baseURL}

	return &API{
		router:     router,
		prefix:     prefixSlashes,
		info:       info,
		marshalers: marshalers,
	}
}
开发者ID:gitter-badger,项目名称:soyfr,代码行数:32,代码来源:api_public.go

示例13: New

// New returns a new *router to be used to configure the endpoints
func New() *Router {
	r := Router{}
	r.router = httprouter.New()
	r.middleware = nil

	return &r
}
开发者ID:bwinterton,项目名称:eden,代码行数:8,代码来源:eden.go

示例14: newStatusServer

// newStatusServer allocates and returns a statusServer.
func newStatusServer(
	db *client.DB,
	gossip *gossip.Gossip,
	metricSource json.Marshaler,
	ctx *base.Context,
	rpcCtx *rpc.Context,
	stores *storage.Stores,
) *statusServer {
	// Create an http client with a timeout
	httpClient, err := ctx.GetHTTPClient()
	if err != nil {
		log.Error(err)
		return nil
	}

	server := &statusServer{
		db:           db,
		gossip:       gossip,
		metricSource: metricSource,
		router:       httprouter.New(),
		rpcCtx:       rpcCtx,
		proxyClient:  httpClient,
		stores:       stores,
	}

	server.router.GET(statusLogFilesListPattern, server.handleLogFilesList)
	server.router.GET(statusLogFilePattern, server.handleLogFile)
	server.router.GET(statusLogsPattern, server.handleLogs)
	// TODO(tschottdorf): significant overlap with /debug/pprof/goroutine,
	// except that this one allows querying by NodeID.
	server.router.GET(statusStacksPattern, server.handleStacks)
	server.router.GET(statusMetricsPattern, server.handleMetrics)

	return server
}
开发者ID:JKhawaja,项目名称:cockroach,代码行数:36,代码来源:status.go

示例15: main

func main() {
	Values[1] = "z"
	Values[2] = "y"
	Values[3] = "x"
	Values[4] = "q"
	Values[5] = "w"
	Values[6] = "v"
	Values[7] = "u"
	Values[8] = "t"
	Values[9] = "s"
	Values[10] = "r"

	for _, each := range ListOfServers {
		HashingMapping[calculateHashValue(each)] = each
	}

	for k, _ := range Values {
		HashingMapping[calculateHashValue(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range HashingMapping {
		SortedHashingMappingKeys = append(SortedHashingMappingKeys, k)
	}

	sort.Strings(SortedHashingMappingKeys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", putDataTo)
	mux.GET("/keys/:key", getRequest)
	server := http.Server{
		Addr:    "0.0.0.0:8000",
		Handler: mux,
	}
	server.ListenAndServe()
}
开发者ID:vibhutisha,项目名称:CmpE273_Lab3,代码行数:34,代码来源:Client.go


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