示例#1
0
文件: web.go 项目: tiaotiao/web
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
0
func mustGetPathTemplate(route *mux.Route) string {
	t, err := route.GetPathTemplate()
	if err != nil {
		panic(err)
	}
	return t
}
示例#3
0
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
0
文件: urls.go 项目: MjAbuz/docker
// 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
0
// 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
0
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
0
文件: api.go 项目: trusch/restless
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
0
// 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
0
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
0
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
0
文件: api.go 项目: clobrano/snappy
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
0
// 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
0
文件: server.go 项目: tayzlor/traefik
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
0
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
0
文件: web.go 项目: arlm/diplicity
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
	})
}
示例#16
0
// Init - Initialize application
func InitEndpointsHandlers(globals *config.Globals, parentRotuer *mux.Route) {
	router := parentRotuer.Subrouter()
	router.HandleFunc("/", SecurityContextHandler(endpointsPageHandler, globals, "ADMIN"))
	router.HandleFunc("/{name}", SecurityContextHandler(endpointPageHandler, globals, "ADMIN"))
	router.HandleFunc("/{name}/{action}", SecurityContextHandler(endpointActionPageHandler, globals, "ADMIN"))
}
示例#17
0
func (m Match) SetRoute(r *mux.Route) *mux.Route {
	if m.Prefix != "" {
		r = r.PathPrefix(m.Prefix)
	}
	if m.Hosts != nil && len(m.Hosts) > 0 {
		for _, host := range m.Hosts {
			r = r.Host(host)
		}
	}
	if m.Methods != nil && len(m.Methods) > 0 {
		r = r.Methods(m.Methods...)
	}
	if m.Schemes != nil && len(m.Schemes) > 0 {
		for _, scheme := range m.Schemes {
			r = r.Schemes(scheme)
		}
	}
	if m.Queries != nil && len(m.Queries) > 0 {
		for _, m := range m.Queries {
			for k, v := range m {
				r = r.Queries(k, v)
			}
		}
	}
	if m.Headers != nil && len(m.Headers) > 0 {
		for _, m := range m.Headers {
			for k, v := range m {
				r = r.Headers(k, v)
			}
		}
	}
	if m.Custom != nil && len(m.Custom) > 0 {
		// lookup custom function by name
		// func(r *http.Request, rm *RouteMatch) bool
	}
	return r
}
示例#18
0
// PrintRoutes Attempts to print all register routes when called using mux.Router.Walk(PrintRoutes)
func PrintRoutes(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
	url, _ := route.URL()
	fmt.Println(route.GetName(), url)
	return nil
}
示例#19
0
// Init - Initialize application
func InitStatsHandlers(globals *config.Globals, parentRotuer *mux.Route) {
	router := parentRotuer.Subrouter()
	router.HandleFunc("/", SecurityContextHandler(statsPageHandler, globals, ""))
	router.HandleFunc("/server", ContextHandler(statsServerPageHandler, globals))
	router.HandleFunc("/admin", ContextHandler(statsAdminPageHandler, globals))
}
示例#20
0
// Init - Initialize application
func InitUsersHandlers(globals *config.Globals, parentRotuer *mux.Route) {
	router := parentRotuer.Subrouter()
	router.HandleFunc("/{login}", SecurityContextHandler(userPageHandler, globals, "ADMIN"))
	router.HandleFunc("/", SecurityContextHandler(usersPageHandler, globals, "ADMIN"))
}
func (this *WebContentController) Register(route *mux.Route) { // {{{
	route.PathPrefix("/")
} // }}}
示例#22
0
// Init - Initialize application
func InitCertsHandlers(globals *config.Globals, parentRotuer *mux.Route) {
	router := parentRotuer.Subrouter()
	router.HandleFunc("/", SecurityContextHandler(certsPageHandler, globals, "ADMIN"))
	router.HandleFunc("/upload", SecurityContextHandler(certUploadPageHandler, globals, "ADMIN")).Methods("POST")
	router.HandleFunc("/delete", SecurityContextHandler(certDeletePageHandler, globals, "ADMIN"))
}
示例#23
0
文件: mux.go 项目: gorward/mux
// HANDLER create route using GorwardRouter values
func (r GowardRouter) Handler(handler http.Handler) Router {
	var route *mux.Route

	if r.FMiddleware != nil {
		handler = bindMiddlewares(handler, r.FMiddleware...)
	}

	if r.FPath == "/" && r.FParentRouter != nil {
		route = r.FParentRouter.NewRoute()
		route = route.Path(r.FPrefix)
	} else {
		route = r.FRouter.NewRoute()
		route.Path(r.FPath)
	}
	if r.FHost != "" {
		route = route.Host(r.FHost)
	}
	if r.Methods != nil {
		route = route.Methods(r.FMethods...)
	}

	route.Handler(handler)

	return r
}
示例#24
0
文件: gitbot.go 项目: knivey/gitbot
func (_ gitHandler) Route(r *mux.Route) {
	r.Path("/").Methods("POST").Headers(
		"Content-Type", "application/json",
		"X-GITHUB-EVENT", "",
	)
}
示例#25
0
// Init - Initialize application
func InitSettingsHandlers(globals *config.Globals, parentRotuer *mux.Route) {
	router := parentRotuer.Subrouter()
	router.HandleFunc("/", SecurityContextHandler(settingsPageHandler, globals, "ADMIN"))
	router.HandleFunc("/setdebug", SecurityContextHandler(setdebugPageHandler, globals, "ADMIN"))
	router.HandleFunc("/confreload", SecurityContextHandler(confReloadPageHandler, globals, "ADMIN"))
}