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


Golang Router.HandleFunc方法代码示例

本文整理汇总了Golang中github.com/gorilla/mux.Router.HandleFunc方法的典型用法代码示例。如果您正苦于以下问题:Golang Router.HandleFunc方法的具体用法?Golang Router.HandleFunc怎么用?Golang Router.HandleFunc使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/gorilla/mux.Router的用法示例。


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

示例1: main

func main() {

	var (
		redisAddress string
		router       *mux.Router
		err          error
		port         int
	)

	flag.IntVar(&port, "port", 4242, "Local port to listen on")
	flag.StringVar(&redisAddress, "redis-address", "localhost:6379", "Redis server address (host:port)")
	flag.Parse()

	if redisConn, err = redis.NewRedis(redisAddress); err != nil {
		log.Fatalf("Unable to connect to Redis server at %v\n", redisAddress)
	}
	log.Printf("Connected to Redis server at %v\n", redisAddress)

	router = mux.NewRouter()
	router.HandleFunc("/entries/{category}", GetEntries).Methods("GET")
	router.HandleFunc("/add/{category}", AddEntry).Methods("POST")
	http.Handle("/", router)

	log.Printf("Listening on http://localhost:%v\n", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
开发者ID:marthjod,项目名称:squatistics,代码行数:26,代码来源:main.go

示例2: Home

func Home(r *mux.Router) {

	//home
	r.HandleFunc("/home", func(w http.ResponseWriter, req *http.Request) {
		view(w, "index", "Eu sou a mensagem exemplo")
	})
}
开发者ID:vitormoura,项目名称:Laboratorio,代码行数:7,代码来源:home.go

示例3: AddPingRoute

// AddPingRoute adds an optimized ping route to the given router
func AddPingRoute(router *mux.Router) *mux.Route {
	return router.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"pong":true}`))
	}).Methods("GET", "HEAD", "OPTIONS")
}
开发者ID:oliverbestmann,项目名称:go-minion,代码行数:8,代码来源:routes.go

示例4: Mount

// Mount adds CRUD and OPTIONS routes to the router, which rely on the given Storage. You can provide a middleware function auth that authenticates and authorizes requests.
func Mount(router *mux.Router, storage Storage, auth func(http.HandlerFunc) http.HandlerFunc) {
	if storage == nil {
		panic("storage is nil")
	}

	if auth == nil {
		auth = func(f http.HandlerFunc) http.HandlerFunc { return f }
	}

	collectionHandlers := map[string]apiHandlerFunc{
		"GET":     getAll,
		"POST":    create,
		"DELETE":  deleteAll,
		"OPTIONS": optionsCollection,
	}

	resourceHandlers := map[string]apiHandlerFunc{
		"GET":     get,
		"PUT":     update,
		"DELETE":  del,
		"OPTIONS": optionsResource,
	}

	router.HandleFunc("/{collection}", auth(chooseAndInitialize(collectionHandlers, storage)))
	router.HandleFunc("/{collection}/{id}", auth(chooseAndInitialize(resourceHandlers, storage)))
}
开发者ID:sauerbraten,项目名称:crudapi,代码行数:27,代码来源:api.go

示例5: Register

func Register(rtr *mux.Router, bus *eventbus.EventBus) {
	rtr.HandleFunc("/ws", upgradeHandler).Methods("GET")
	bus.RegisterHandler(serviceStateChanged)
	bus.RegisterHandler(viewStateChanged)

	go h.run()
}
开发者ID:walmartlabs,项目名称:lovebeat,代码行数:7,代码来源:stream.go

示例6: registerIdentityRoot

func registerIdentityRoot(s *CollectorSuite, r *mux.Router) {
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, `
				{
					"versions": {
						"values": [
							{
								"status": "experimental",
								"id": "v3.0",
								"links": [
									{ "href": "%s", "rel": "self" }
								]
							},
							{
								"status": "stable",
								"id": "v2.0",
								"links": [
									{ "href": "%s", "rel": "self" }
								]
							}
						]
					}
				}
				`, s.server.URL+"/v3/", s.server.URL+"/v2.0/")
	})
}
开发者ID:intelsdi-x,项目名称:snap-plugin-collector-cinder,代码行数:26,代码来源:collector_test.go

示例7: setupWebsiteRoutes

func setupWebsiteRoutes(r *mux.Router) {
	// serve static files
	r.HandleFunc("/static/config.js", webConfigHandler)
	r.PathPrefix("/static").Handler(http.FileServer(http.Dir("web/build/")))

	r.HandleFunc("/version", versionHandler).Methods("GET")

	// docs
	for _, p := range webDocPages {
		r.HandleFunc(p.route, webDocHandler)
	}

	// lists
	r.HandleFunc("/list/{kind}/by-{order}", webListHandler)

	// user
	r.HandleFunc("/{user}", webUserHandler)
	u := r.PathPrefix("/{user}").Subrouter()
	u.StrictSlash(true)

	u.HandleFunc("/", webUserHandler).Methods("GET")
	// u.HandleFunc("/user/add", webUserAddHandler).Methods("POST")
	// u.HandleFunc("/user/info", webUserInfoHandler).Methods("GET", "POST")
	// u.HandleFunc("/user/pass", webUserPassHandler).Methods("POST")

	// user/dataset
	u.HandleFunc("/{dataset}", webDsHomeHandler)
	// d := u.PathPrefix("/{dataset}@{ref}").Subrouter()
	// d.StrictSlash(true)

	// d.HandleFunc("/", webDsHomeHandler)
	// d.HandleFunc("/blob/", webDsBlobHandler)
}
开发者ID:jbenet,项目名称:datadex,代码行数:33,代码来源:datadex_router.go

示例8: registerIdentityTenants

func registerIdentityTenants(s *CollectorSuite, r *mux.Router) {
	r.HandleFunc("/v2.0/tenants", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("X-Auth-Token", s.Token)

		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)

		fmt.Fprintf(w, `
			{
				"tenants": [
					{
						"description": "Test tenat",
						"enabled": true,
						"id": "%s",
						"name": "%s"
					},
					{
						"description": "admin tenant",
						"enabled": true,
						"id": "%s",
						"name": "%s"
					}
				],
				"tenants_links": []
			}
		`, s.Tenant1ID, s.Tenant1Name, s.Tenant2ID, s.Tenant2Name)
	}).Methods("GET")
}
开发者ID:intelsdi-x,项目名称:snap-plugin-collector-cinder,代码行数:28,代码来源:collector_test.go

示例9: registerWebuiHandler

// registerWebuiHandler registers handlers for serving web UI
func registerWebuiHandler(router *mux.Router) {
	// Setup the router to serve the web UI
	goPath := os.Getenv("GOPATH")
	if goPath != "" {
		webPath := goPath + "/src/github.com/contiv/contivmodel/www/"

		// Make sure we have the web UI files
		_, err := os.Stat(webPath)
		if err != nil {
			webPath = goPath + "/src/github.com/contiv/netplugin/" +
				"Godeps/_workspace/src/github.com/contiv/contivmodel/www/"
			_, err := os.Stat(webPath)
			if err != nil {
				log.Errorf("Can not find the web UI directory")
			}
		}

		log.Infof("Using webPath: %s", webPath)

		// serve static files
		router.PathPrefix("/web/").Handler(http.StripPrefix("/web/", http.FileServer(http.Dir(webPath))))

		// Special case to serve main index.html
		router.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
			http.ServeFile(rw, req, webPath+"index.html")
		})
	}

	// proxy Handler
	router.PathPrefix("/proxy/").HandlerFunc(proxyHandler)
}
开发者ID:nikolayvoronchikhin,项目名称:netplugin,代码行数:32,代码来源:main.go

示例10: Register

func Register(rtr *mux.Router, client_ service.ServiceIf) {
	client = client_
	rtr.HandleFunc("/", RedirectHandler).Methods("GET")
	rtr.HandleFunc("/status", StatusHandler).Methods("GET")
	rtr.PathPrefix("/").Handler(http.FileServer(
		&assetfs.AssetFS{Asset, AssetDir, "/"}))
}
开发者ID:walmartlabs,项目名称:lovebeat,代码行数:7,代码来源:dashboard.go

示例11: handlePlayground

func handlePlayground(r *mux.Router) {
	r = r.PathPrefix("/api/playground").Subrouter()

	r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		results.View("playground/form", nil, w)
	})
}
开发者ID:vitormoura,项目名称:Laboratorio,代码行数:7,代码来源:playground.go

示例12: addApiHandlers

// addApiHandlers adds each API handler to the given router.
func addApiHandlers(router *mux.Router, db *sqlx.DB) {
	for route, funcs := range api.ApiHandlers() {
		for method, f := range funcs {
			router.HandleFunc(apiPath+route, auth.Use(wrapApiHandler(f, funcs.Methods(), db), auth.RequireLogin)).Methods(method.String())
		}
	}
}
开发者ID:PSUdaemon,项目名称:playground,代码行数:8,代码来源:routes.go

示例13: AddStatusHandler

func AddStatusHandler(router *mux.Router) {
	router.HandleFunc("/status.txt", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Fprint(rw, "alive")
		return
	})
	return
}
开发者ID:jprobinson,项目名称:go-utils,代码行数:7,代码来源:util.go

示例14: Register

func (md *MandrillWebhook) Register(router *mux.Router, acc telegraf.Accumulator) {
	router.HandleFunc(md.Path, md.returnOK).Methods("HEAD")
	router.HandleFunc(md.Path, md.eventHandler).Methods("POST")

	log.Printf("Started the webhooks_mandrill on %s\n", md.Path)
	md.acc = acc
}
开发者ID:li-ang,项目名称:telegraf,代码行数:7,代码来源:mandrill_webhooks.go

示例15: getNegroniHandlers

func getNegroniHandlers(ctx *RouterContext.RouterContext, router *mux.Router) []negroni.Handler {
	tmpArray := []negroni.Handler{}

	// fullRecoveryStackMessage := GlobalConfigSettings.Common.DevMode

	routerRecoveryWrapper := &tmpRouterRecoveryWrapper{ctx.Logger}

	// tmpArray = append(tmpArray, gzip.Gzip(gzip.DefaultCompression))
	tmpArray = append(tmpArray, NewRecovery(routerRecoveryWrapper.onRouterRecoveryError)) //recovery.JSONRecovery(fullRecoveryStackMessage))
	tmpArray = append(tmpArray, negroni.NewLogger())

	if ctx.Settings.IsDevMode() {
		middleware := stats.New()
		router.HandleFunc("/stats.json", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")

			stats := middleware.Data()

			b, _ := json.Marshal(stats)

			w.Write(b)
		})
		tmpArray = append(tmpArray, middleware)
	}

	return tmpArray
}
开发者ID:francoishill,项目名称:windows-startup-manager,代码行数:27,代码来源:server.go


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