本文整理汇总了Golang中github.com/gorilla/mux.Router类的典型用法代码示例。如果您正苦于以下问题:Golang Router类的具体用法?Golang Router怎么用?Golang Router使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Router类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: InitLicense
func InitLicense(r *mux.Router) {
l4g.Debug("Initializing license api routes")
sr := r.PathPrefix("/license").Subrouter()
sr.Handle("/add", ApiAdminSystemRequired(addLicense)).Methods("POST")
sr.Handle("/remove", ApiAdminSystemRequired(removeLicense)).Methods("POST")
}
开发者ID:mokamo,项目名称:platform,代码行数:7,代码来源:license.go
示例2: wrapRouter
// Returns a top-level HTTP handler for a Router. This adds behavior for URLs that don't
// match anything -- it handles the OPTIONS method as well as returning either a 404 or 405
// for URLs that don't match a route.
func wrapRouter(sc *ServerContext, privs handlerPrivs, router *mux.Router) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, rq *http.Request) {
fixQuotedSlashes(rq)
var match mux.RouteMatch
if router.Match(rq, &match) {
router.ServeHTTP(response, rq)
} else {
// Log the request
h := newHandler(sc, privs, response, rq)
h.logRequestLine()
// What methods would have matched?
var options []string
for _, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE"} {
if wouldMatch(router, rq, method) {
options = append(options, method)
}
}
if len(options) == 0 {
h.writeStatus(http.StatusNotFound, "unknown URL")
} else {
response.Header().Add("Allow", strings.Join(options, ", "))
if rq.Method != "OPTIONS" {
h.writeStatus(http.StatusMethodNotAllowed, "")
}
}
}
})
}
开发者ID:jnordberg,项目名称:sync_gateway,代码行数:32,代码来源:routing.go
示例3: InitUser
func InitUser(r *mux.Router) {
l4g.Debug("Initializing user api routes")
sr := r.PathPrefix("/users").Subrouter()
sr.Handle("/create", ApiAppHandler(createUser)).Methods("POST")
sr.Handle("/update", ApiUserRequired(updateUser)).Methods("POST")
sr.Handle("/update_roles", ApiUserRequired(updateRoles)).Methods("POST")
sr.Handle("/update_active", ApiUserRequired(updateActive)).Methods("POST")
sr.Handle("/update_notify", ApiUserRequired(updateUserNotify)).Methods("POST")
sr.Handle("/newpassword", ApiUserRequired(updatePassword)).Methods("POST")
sr.Handle("/send_password_reset", ApiAppHandler(sendPasswordReset)).Methods("POST")
sr.Handle("/reset_password", ApiAppHandler(resetPassword)).Methods("POST")
sr.Handle("/login", ApiAppHandler(login)).Methods("POST")
sr.Handle("/logout", ApiUserRequired(logout)).Methods("POST")
sr.Handle("/revoke_session", ApiUserRequired(revokeSession)).Methods("POST")
sr.Handle("/newimage", ApiUserRequired(uploadProfileImage)).Methods("POST")
sr.Handle("/me", ApiAppHandler(getMe)).Methods("GET")
sr.Handle("/status", ApiUserRequiredActivity(getStatuses, false)).Methods("GET")
sr.Handle("/profiles", ApiUserRequired(getProfiles)).Methods("GET")
sr.Handle("/profiles/{id:[A-Za-z0-9]+}", ApiUserRequired(getProfiles)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}", ApiUserRequired(getUser)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}/sessions", ApiUserRequired(getSessions)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}/audits", ApiUserRequired(getAudits)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}/image", ApiUserRequired(getProfileImage)).Methods("GET")
}
开发者ID:nikwins,项目名称:platform,代码行数:27,代码来源:user.go
示例4: 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
示例5: setupMuxHandlers
func (me *endPoint) setupMuxHandlers(mux *mux.Router) {
fn := handleIncoming(me)
m := interpose.New()
for i, _ := range me.modules {
m.Use(me.modules[i])
//fmt.Println("using module:", me.modules[i], reflect.TypeOf(me.modules[i]))
}
m.UseHandler(http.HandlerFunc(fn))
if me.info.Version == "*" {
mux.Handle(me.muxUrl, m).Methods(me.httpMethod)
} else {
urlWithVersion := cleanUrl(me.info.Prefix, "v"+me.info.Version, me.muxUrl)
urlWithoutVersion := cleanUrl(me.info.Prefix, me.muxUrl)
// versioned url
mux.Handle(urlWithVersion, m).Methods(me.httpMethod)
// content type (style1)
header1 := fmt.Sprintf("application/%s-v%s+json", me.info.Vendor, me.info.Version)
mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header1)
// content type (style2)
header2 := fmt.Sprintf("application/%s+json;version=%s", me.info.Vendor, me.info.Version)
mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header2)
}
}
开发者ID:tolexo,项目名称:aqua,代码行数:29,代码来源:endpoint.go
示例6: SetAuthenticationRoutes
func SetAuthenticationRoutes(router *mux.Router) *mux.Router {
tokenRouter := mux.NewRouter()
tokenRouter.Handle("/api/auth/token/new", negroni.New(
negroni.HandlerFunc(controllers.Login),
)).Methods("POST")
tokenRouter.Handle("/api/auth/logout", negroni.New(
negroni.HandlerFunc(auth.RequireTokenAuthentication),
negroni.HandlerFunc(controllers.Logout),
))
tokenRouter.Handle("/api/auth/token/refresh", negroni.New(
negroni.HandlerFunc(auth.RequireTokenAuthentication),
negroni.HandlerFunc(controllers.RefreshToken),
)).Methods("GET")
tokenRouter.Handle("/api/auth/token/validate", negroni.New(
negroni.HandlerFunc(auth.RequireTokenAuthentication),
negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.WriteHeader(http.StatusOK)
}),
))
router.PathPrefix("/api/auth").Handler(negroni.New(
negroni.Wrap(tokenRouter),
))
return router
}
开发者ID:malloc-fi,项目名称:vantaa,代码行数:31,代码来源:authentication.go
示例7: 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
示例8: 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
示例9: addRoutesToRouter
func (this V1HttpApi) addRoutesToRouter(router *mux.Router) {
v1 := router.PathPrefix("/v1/").Subrouter()
v1.HandleFunc("/log/{__level}/{__category}/{__slug}/", this.PostLogHandler).Methods("POST")
v1.HandleFunc("/log/bulk/", this.PostBulkLogHandler).Methods("POST")
v1.HandleFunc("/ping", this.PingHandler)
v1.HandleFunc("/ping/", this.PingHandler)
}
开发者ID:KSCTECHNOLOGIES,项目名称:uberlog,代码行数:7,代码来源:http_api.go
示例10: TestErrorExpectedResponse
// TestErrorExpectedResponse is the generic test code for testing for a bad response
func TestErrorExpectedResponse(t *testing.T, router *mux.Router, method, url, route string, data io.Reader, accessToken, msg string, code int, assertExpectations func()) {
// Prepare a request
r, err := http.NewRequest(
method,
url,
data,
)
assert.NoError(t, err)
// Optionally add a bearer token to headers
if accessToken != "" {
r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
}
// Check the routing
match := new(mux.RouteMatch)
router.Match(r, match)
if assert.NotNil(t, match.Route) {
assert.Equal(t, route, match.Route.GetName())
}
// And serve the request
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
TestResponseForError(t, w, msg, code)
assertExpectations()
}
开发者ID:RichardKnop,项目名称:example-api,代码行数:30,代码来源:helpers.go
示例11: InitAdmin
func InitAdmin(r *mux.Router) {
l4g.Debug("Initializing admin api routes")
sr := r.PathPrefix("/admin").Subrouter()
sr.Handle("/logs", ApiUserRequired(getLogs)).Methods("GET")
sr.Handle("/client_props", ApiAppHandler(getClientProperties)).Methods("GET")
}
开发者ID:saitodisse,项目名称:platform,代码行数:7,代码来源:admin.go
示例12: 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
示例13: AddRoutes
// AddRoutes adds routes to a router instance. If there are middlewares defined
// for a route, a new negroni app is created and wrapped as a http.Handler
func AddRoutes(routes []Route, router *mux.Router) {
var (
handler http.Handler
n *negroni.Negroni
)
for _, route := range routes {
// Add any specified middlewares
if len(route.Middlewares) > 0 {
n = negroni.New()
for _, middleware := range route.Middlewares {
n.Use(middleware)
}
// Wrap the handler in the negroni app with middlewares
n.Use(negroni.Wrap(route.HandlerFunc))
handler = n
} else {
handler = route.HandlerFunc
}
router.Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
}
开发者ID:RichardKnop,项目名称:example-api,代码行数:30,代码来源:routes.go
示例14: CompaniesInterfaceRoutes
func CompaniesInterfaceRoutes(r *mux.Router, i CompaniesInterface) {
r.HandleFunc("/companies", i.Post).Methods("POST")
r.HandleFunc("/companies/{globalId}", i.globalIdPut).Methods("PUT")
r.HandleFunc("/companies/{globalId}/validate", i.globalIdvalidateGet).Methods("GET")
r.HandleFunc("/companies/{globalId}/contracts", i.globalIdcontractsGet).Methods("GET")
r.HandleFunc("/companies/{globalId}/info", i.globalIdinfoGet).Methods("GET")
}
开发者ID:mohabusama,项目名称:identityserver,代码行数:7,代码来源:companies_if.go
示例15: registerCloudStorageAPI
// registerCloudStorageAPI - register all the handlers to their respective paths
func registerCloudStorageAPI(mux *router.Router, a CloudStorageAPI) {
root := mux.NewRoute().PathPrefix("/").Subrouter()
bucket := root.PathPrefix("/{bucket}").Subrouter()
bucket.Methods("HEAD").Path("/{object:.+}").HandlerFunc(a.HeadObjectHandler)
bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(a.PutObjectPartHandler).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(a.ListObjectPartsHandler).Queries("uploadId", "{uploadId:.*}")
bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(a.CompleteMultipartUploadHandler).Queries("uploadId", "{uploadId:.*}")
bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(a.NewMultipartUploadHandler).Queries("uploads", "")
bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(a.AbortMultipartUploadHandler).Queries("uploadId", "{uploadId:.*}")
bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(a.GetObjectHandler)
bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(a.PutObjectHandler)
bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(a.DeleteObjectHandler)
bucket.Methods("GET").HandlerFunc(a.GetBucketACLHandler).Queries("acl", "")
bucket.Methods("GET").HandlerFunc(a.ListMultipartUploadsHandler).Queries("uploads", "")
bucket.Methods("GET").HandlerFunc(a.ListObjectsHandler)
bucket.Methods("PUT").HandlerFunc(a.PutBucketACLHandler).Queries("acl", "")
bucket.Methods("PUT").HandlerFunc(a.PutBucketHandler)
bucket.Methods("HEAD").HandlerFunc(a.HeadBucketHandler)
bucket.Methods("POST").HandlerFunc(a.PostPolicyBucketHandler)
bucket.Methods("DELETE").HandlerFunc(a.DeleteBucketHandler)
root.Methods("GET").HandlerFunc(a.ListBucketsHandler)
}
开发者ID:masu-mi,项目名称:minio,代码行数:26,代码来源:routers.go
示例16: 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
示例17: 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
示例18: restAPI
func restAPI(r *mux.Router) {
sr := r.PathPrefix("/_api/").MatcherFunc(adminRequired).Subrouter()
sr.HandleFunc("/buckets",
restGetBuckets).Methods("GET")
sr.HandleFunc("/buckets",
restPostBucket).Methods("POST")
sr.HandleFunc("/buckets/{bucketname}",
restGetBucket).Methods("GET")
sr.HandleFunc("/buckets/{bucketname}",
restDeleteBucket).Methods("DELETE")
sr.HandleFunc("/buckets/{bucketname}/compact",
restPostBucketCompact).Methods("POST")
sr.HandleFunc("/buckets/{bucketname}/flushDirty",
restPostBucketFlushDirty).Methods("POST")
sr.HandleFunc("/buckets/{bucketname}/stats",
restGetBucketStats).Methods("GET")
sr.HandleFunc("/bucketsRescan",
restPostBucketsRescan).Methods("POST")
sr.HandleFunc("/profile/cpu",
restProfileCPU).Methods("POST")
sr.HandleFunc("/profile/memory",
restProfileMemory).Methods("POST")
sr.HandleFunc("/runtime",
restGetRuntime).Methods("GET")
sr.HandleFunc("/runtime/memStats",
restGetRuntimeMemStats).Methods("GET")
sr.HandleFunc("/runtime/gc",
restPostRuntimeGC).Methods("POST")
sr.HandleFunc("/settings",
restGetSettings).Methods("GET")
r.PathPrefix("/_api/").HandlerFunc(authError)
}
开发者ID:scottcagno,项目名称:cbgb,代码行数:33,代码来源:rest.go
示例19: RegisterControlRoutes
// RegisterControlRoutes registers the various control routes with a http mux.
func RegisterControlRoutes(router *mux.Router) {
controlRouter := &controlRouter{
probes: map[string]controlHandler{},
}
router.Methods("GET").Path("/api/control/ws").HandlerFunc(controlRouter.handleProbeWS)
router.Methods("POST").MatcherFunc(URLMatcher("/api/control/{probeID}/{nodeID}/{control}")).HandlerFunc(controlRouter.handleControl)
}
开发者ID:rnd-ua,项目名称:scope,代码行数:8,代码来源:controls.go
示例20: NewHandler
func NewHandler(s api.FluxService, r *mux.Router, logger log.Logger, h metrics.Histogram) http.Handler {
for method, handlerFunc := range map[string]func(api.FluxService) http.Handler{
"ListServices": handleListServices,
"ListImages": handleListImages,
"PostRelease": handlePostRelease,
"GetRelease": handleGetRelease,
"Automate": handleAutomate,
"Deautomate": handleDeautomate,
"Lock": handleLock,
"Unlock": handleUnlock,
"History": handleHistory,
"GetConfig": handleGetConfig,
"SetConfig": handleSetConfig,
"RegisterDaemon": handleRegister,
"IsConnected": handleIsConnected,
} {
var handler http.Handler
handler = handlerFunc(s)
handler = logging(handler, log.NewContext(logger).With("method", method))
handler = observing(handler, h.With("method", method))
r.Get(method).Handler(handler)
}
return r
}
开发者ID:weaveworks,项目名称:flux,代码行数:25,代码来源:transport.go
注:本文中的github.com/gorilla/mux.Router类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论