當前位置: 首頁>>代碼示例>>Golang>>正文


Golang mux.Route類代碼示例

本文整理匯總了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
}
開發者ID:tiaotiao,項目名稱:web,代碼行數:30,代碼來源:web.go

示例2: mustGetPathTemplate

func mustGetPathTemplate(route *mux.Route) string {
	t, err := route.GetPathTemplate()
	if err != nil {
		panic(err)
	}
	return t
}
開發者ID:weaveworks,項目名稱:flux,代碼行數:7,代碼來源:transport.go

示例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
}
開發者ID:pombredanne,項目名稱:snappy-1,代碼行數:30,代碼來源:api.go

示例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)
}
開發者ID:MjAbuz,項目名稱:docker,代碼行數:10,代碼來源:urls.go

示例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()
}
開發者ID:General-Beck,項目名稱:snappy,代碼行數:12,代碼來源:task.go

示例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))
}
開發者ID:juanluisvaladas,項目名稱:origin,代碼行數:8,代碼來源:app.go

示例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")
}
開發者ID:trusch,項目名稱:restless,代碼行數:9,代碼來源:api.go

示例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)
	}
}
開發者ID:seanstrickland-wf,項目名稱:go-rest,代碼行數:10,代碼來源:api.go

示例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
}
開發者ID:diffeo,項目名稱:go-coordinate,代碼行數:14,代碼來源:helpers.go

示例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
}
開發者ID:diffeo,項目名稱:go-coordinate,代碼行數:15,代碼來源:helpers.go

示例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)
}
開發者ID:clobrano,項目名稱:snappy,代碼行數:19,代碼來源:api.go

示例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")
}
開發者ID:johnnadratowski,項目名稱:resourceful,代碼行數:44,代碼來源:resourceful.go

示例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)
	}
}
開發者ID:tayzlor,項目名稱:traefik,代碼行數:25,代碼來源:server.go

示例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
}
開發者ID:natural,項目名稱:missmolly,代碼行數:22,代碼來源:location.go

示例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
	})
}
開發者ID:arlm,項目名稱:diplicity,代碼行數:36,代碼來源:web.go


注:本文中的github.com/gorilla/mux.Route類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。