本文整理汇总了Golang中github.com/gorilla/mux.Route类的典型用法代码示例。如果您正苦于以下问题:Golang Route类的具体用法?Golang Route怎么用?Golang Route使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Route类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handle
func (w *Web) handle(method, urlpath string, fn Handler, midwares *MiddlewaresManager) {
var h *handler
h = newHandler(fn, midwares, w.responser, w.logger)
// match prefix
var prefix bool
if strings.HasSuffix(urlpath, "*") {
urlpath = strings.TrimSuffix(urlpath, "*")
prefix = true
}
// register mux route
var rt *mux.Route
if prefix {
rt = w.mux.PathPrefix(urlpath).Handler(h)
} else {
rt = w.mux.Handle(urlpath, h)
}
rt.Methods(strings.ToUpper(method))
// add to map
url := methodUrl(method, urlpath)
_, ok := w.handlers[url]
if ok {
panic("url conflict: " + url)
}
w.handlers[url] = h
return
}
示例2: mustGetPathTemplate
func mustGetPathTemplate(route *mux.Route) string {
t, err := route.GetPathTemplate()
if err != nil {
panic(err)
}
return t
}
示例3: webify
func webify(result map[string]string, resource string) map[string]string {
result["resource"] = resource
icon := result["icon"]
if icon == "" || strings.HasPrefix(icon, "http") {
return result
}
result["icon"] = ""
var route *mux.Route
var args []string
if strings.HasPrefix(icon, dirs.SnapIconsDir) {
route = metaIconCmd.d.router.Get(metaIconCmd.Path)
args = []string{"icon", icon[len(dirs.SnapIconsDir)+1:]}
} else {
route = appIconCmd.d.router.Get(appIconCmd.Path)
args = []string{"name", result["name"], "origin", result["origin"]}
}
if route != nil {
url, err := route.URL(args...)
if err == nil {
result["icon"] = url.String()
}
}
return result
}
示例4: cloneRoute
// clondedRoute returns a clone of the named route from the router. Routes
// must be cloned to avoid modifying them during url generation.
func (ub *URLBuilder) cloneRoute(name string) *mux.Route {
route := new(mux.Route)
*route = *ub.router.GetRoute(name) // clone the route
return route.
Schemes(ub.root.Scheme).
Host(ub.root.Host)
}
示例5: Location
// Location of the task, based on the given route.
//
// If the route can't build a URL for this task, returns the empty
// string.
func (t *Task) Location(route *mux.Route) string {
url, err := route.URL("uuid", t.id.String())
if err != nil {
return ""
}
return url.String()
}
示例6: RegisterRoute
func (app *App) RegisterRoute(route *mux.Route, dispatch dispatchFunc, nameRequired nameRequiredFunc, accessRecords customAccessRecordsFunc) {
// TODO(stevvooe): This odd dispatcher/route registration is by-product of
// some limitations in the gorilla/mux router. We are using it to keep
// routing consistent between the client and server, but we may want to
// replace it with manual routing and structure-based dispatch for better
// control over the request execution.
route.Handler(app.dispatcher(dispatch, nameRequired, accessRecords))
}
示例7: BuildEndpoint
func BuildEndpoint(route *mux.Route, modelName string, jsEngine *js.JSEngine, db *leveldb.DB) {
router := route.Subrouter()
router.StrictSlash(true)
router.HandleFunc("/{id:.+}", buildGetOneHandler(modelName, jsEngine)).Methods("GET")
router.HandleFunc("/{id:.+}", buildPutOneHandler(modelName, jsEngine)).Methods("PUT")
router.HandleFunc("/{id:.+}", buildDeleteOneHandler(modelName, jsEngine)).Methods("DELETE")
router.HandleFunc("/", buildGetAllHandler(modelName, db)).Methods("GET")
router.HandleFunc("/", buildPostHandler(modelName, jsEngine)).Methods("POST")
}
示例8: checkRoute
// Check the route for an error and log the error if it exists.
func (r *muxAPI) checkRoute(handler, method, uri string, route *mux.Route) {
err := route.GetError()
if err != nil {
log.Printf("Failed to setup route %s with %v", uri, err)
} else {
r.config.Debugf("Registered %s handler at %s %s", handler, method, uri)
}
}
示例9: URL
func (u *urlBuilder) URL(out *string, route string) *urlBuilder {
var r *mux.Route
var url *url.URL
if u.Error == nil {
r = u.Route(route)
}
if u.Error == nil {
url, u.Error = r.URL(u.Params...)
}
if u.Error == nil {
*out = url.String()
}
return u
}
示例10: Template
func (u *urlBuilder) Template(out *string, route, param string) *urlBuilder {
var r *mux.Route
var url *url.URL
if u.Error == nil {
r = u.Route(route)
}
if u.Error == nil {
params := append([]string{param, "---"}, u.Params...)
url, u.Error = r.URL(params...)
}
if u.Error == nil {
*out = strings.Replace(url.String(), "---", "{"+param+"}", 1)
}
return u
}
示例11: sendStorePackages
func sendStorePackages(route *mux.Route, meta *Meta, found []*snap.Info) Response {
results := make([]*json.RawMessage, 0, len(found))
for _, x := range found {
url, err := route.URL("name", x.Name())
if err != nil {
logger.Noticef("Cannot build URL for snap %q revision %s: %v", x.Name(), x.Revision, err)
continue
}
data, err := json.Marshal(webify(mapRemote(x), url.String()))
if err != nil {
return InternalError("%v", err)
}
raw := json.RawMessage(data)
results = append(results, &raw)
}
return SyncResponse(results, meta)
}
示例12: setItemRoutes
// Sets up all of the mux router routes for the items in the given resource
func (rm *ResourceManager) setItemRoutes(res Resource, itemOnly bool) {
var (
router *mux.Router
itemRoute *mux.Route
)
if itemOnly {
// If this resource has no "list", just use ResourceManager
// or parent item router
parent := res.ResourceParent()
router = rm.Router
if parent != nil {
// If this is a child resource, use it's parent item router as a sub router
router = rm.GetRoute(parent, "item").Subrouter()
}
itemRoute = router.PathPrefix(fmt.Sprintf("/%s/", res.ResourceName()))
} else {
// Else this has a list, so use the list router
router = rm.GetRoute(res, "list").Subrouter()
// In case of a list, use the regex specified for the id
idFormat := res.ResourceFullName()
if matcher, ok := res.(ResourceIdMatcher); ok {
// If there is a custom regex match for the ID on this resource,
// add that to the pathprefix for the URL
regex := matcher.ResourceIdMatcher()
if regex != "" {
idFormat = strings.Join([]string{idFormat, regex}, ":")
}
}
itemRoute = router.PathPrefix(fmt.Sprintf("/{%s}/", idFormat))
}
itemRoute = itemRoute.Name(res.ResourceFullName() + "." + "item")
rm.RegisterRoute(res, "item", itemRoute)
rm.setMethodRoutes(res, "Item")
}
示例13: wireFrontendBackend
func (server *Server) wireFrontendBackend(routes map[string]types.Route, newRoute *mux.Route, handler http.Handler) {
// strip prefix
var strip bool
for _, route := range routes {
switch route.Rule {
case "PathStrip":
newRoute.Handler(&middlewares.StripPrefix{
Prefix: route.Value,
Handler: handler,
})
strip = true
break
case "PathPrefixStrip":
newRoute.Handler(&middlewares.StripPrefix{
Prefix: route.Value,
Handler: handler,
})
strip = true
break
}
}
if !strip {
newRoute.Handler(handler)
}
}
示例14: SetContentHandler
func (d *LocationDirective) SetContentHandler(c api.Server, r *mux.Route) *mux.Route {
//
r = r.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
L := c.NewLuaState(w, r)
defer L.Close()
// if file, read once and set string
err := L.DoFile("test.lua")
// if string, set string
// if value in handler map, set handler
// if values in handler map, set handlers
if err != nil {
log.Error("server.request.lua", "path", r.URL, "error", err)
}
})
return r
}
示例15: Handle
func (self *Web) Handle(r *mux.Route, f func(c *HTTPContext) error) {
r.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rw := &responseWriter{
ResponseWriter: w,
request: r,
start: time.Now(),
status: 200,
web: self,
}
for _, encoding := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
if strings.TrimSpace(encoding) == "gzip" {
rw.gzipWriter = gzip.NewWriter(rw.ResponseWriter)
rw.ResponseWriter.Header().Set("Content-Encoding", "gzip")
defer rw.Close()
break
}
}
var i int64
defer func() {
atomic.StoreInt64(&i, 1)
rw.log(recover())
}()
go func() {
time.Sleep(time.Second)
if atomic.CompareAndSwapInt64(&i, 0, 1) {
rw.inc()
}
}()
if err := f(self.GetContext(rw, r)); err != nil {
rw.WriteHeader(500)
fmt.Fprintln(rw, err)
self.Errorf("%v", err)
}
return
})
}