本文整理匯總了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))
}
示例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")
})
}
示例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")
}
示例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)))
}
示例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()
}
示例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/")
})
}
示例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)
}
示例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")
}
示例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)
}
示例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, "/"}))
}
示例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)
})
}
示例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())
}
}
}
示例13: AddStatusHandler
func AddStatusHandler(router *mux.Router) {
router.HandleFunc("/status.txt", func(rw http.ResponseWriter, r *http.Request) {
fmt.Fprint(rw, "alive")
return
})
return
}
示例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
}
示例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
}