Beispiel #1
0
// Router adds panel routes to an existing mux.Router.
func UIRouter(theBaseHref string, rt *mux.Router) *mux.Router {
	baseHref = theBaseHref
	rt.Path("/calls").Methods("GET").HandlerFunc(uiCalls).Name(appmonUICalls)
	rt.Path("/").Methods("GET").HandlerFunc(uiMain).Name(appmonUIMain)

	return rt
}
Beispiel #2
0
func InitAnswerRoutes(r *mux.Router) *mux.Router {

	//PUT
	r.Path("/{category:[a-z]+}/{questionID:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/answer}").Methods("PUT").Name(CreatePendingAnswer)

	r.Path("/{category:[a-z]+}/answer/{answerID:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/vote/{vote:-1|1}}").Methods("PUT").Name(UpdateAnswerVote)
	return r
}
Beispiel #3
0
// PopulateRouter adds all Coordinate URL paths to a router.
func (api *restAPI) PopulateRouter(r *mux.Router) {
	api.PopulateNamespace(r)
	r.Path("/").Name("root").Handler(&resourceHandler{
		Representation: restdata.RootData{},
		Context:        api.Context,
		Get:            api.RootDocument,
	})
}
Beispiel #4
0
func setupApiApps(apirouter *mux.Router, domainmgr DomainManager, usermgr UserManager) {
	prefix, _ := apirouter.Path("/").URL()
	apirouter.PathPrefix("/v1").Handler(
		context.ClearHandler(HandlerList{
			SilentHandler(SessionHandler(options.SessionStore, int(options.SessionTTL/time.Second))),
			SilentHandler(BasicAuth(usermgr)),
			SilentHandler(ValidateUID(usermgr)),
			http.StripPrefix(prefix.Path+"v1", NewAPIv1(domainmgr, usermgr)),
		}))
}
Beispiel #5
0
/*
DocHandle registeres a path/method/api version route in the provided router, handled by the provided f, wrapping it in appstats.NewHandler,
registering the f-function and its route with jsoncontext.Document and then using jsoncontext.Handle to do something that acts like
JSONHandlerFunc.
*/
func DocHandle(router *mux.Router, f interface{}, path string, method string, minAPIVersion, maxAPIVersion int, scopes ...string) {
	doc, fu := jsoncontext.Document(f, path, method, minAPIVersion, maxAPIVersion, scopes...)
	jsoncontext.Remember(doc)
	router.Path(path).Methods(method).Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gaeCont := appengine.NewContext(r)
		c := NewJSONContext(gaeCont, jsoncontext.NewJSONContext(httpcontext.NewHTTPContext(w, r)))
		jsoncontext.Handle(c, func() (resp jsoncontext.Resp, err error) {
			return fu(c)
		}, minAPIVersion, maxAPIVersion, scopes...)
	}))
}
Beispiel #6
0
func (a *AgentCommand) dashboardRoutes(r *mux.Router) {
	r.Path("/" + dashboardPathPrefix).HandlerFunc(a.dashboardIndexHandler)
	subui := r.PathPrefix("/" + dashboardPathPrefix).Subrouter()
	subui.HandleFunc("/jobs", a.dashboardJobsHandler)
	subui.HandleFunc("/jobs/{job}/executions", a.dashboardExecutionsHandler)

	// Path of static files must be last!
	r.PathPrefix("/dashboard").Handler(
		http.StripPrefix("/dashboard", http.FileServer(
			http.Dir(filepath.Join(a.config.UIDir, "static")))))
}
Beispiel #7
0
func ServStatic(router *mux.Router) {

	statikFS, se := fs.New()
	if se != nil {
		log.Fatalf(se.Error())
	}

	// statikFS := http.Dir(filepath.Join(Settings.Root, "htdocs"))
	ss := http.FileServer(statikFS)
	router.PathPrefix("/static/").Handler(ss).Methods("GET", "HEAD")
	router.Path("/favicon.ico").Handler(ss).Methods("GET", "HEAD")
	router.Path("/robots.txt").Handler(ss).Methods("GET", "HEAD")

}
Beispiel #8
0
func Routes(r *mux.Router) {
	ps := r.Path("/paintings").Subrouter()
	ps.Methods("GET").Handler(listPaintings)
	ps.Methods("POST").Handler(createPainting)

	r.Methods("GET").Path("/paintings/categories").Handler(listCategories)
	r.Methods("GET").Path("/paintings/media").Handler(listMedia)

	p := r.Path("/paintings/{ID:[0-9]+}").Subrouter()
	p.Methods("GET").Handler(showPainting)
	p.Methods("PUT").Handler(editPainting)

	r.Methods("POST").Path("/paintings/{ID:[0-9]+}/rotate").Handler(rotatePainting)
}
Beispiel #9
0
func (m *overchanMiddleware) SetupRoutes(mux *mux.Router) {
	// setup front page handler
	mux.Path("/").HandlerFunc(m.ServeIndex)
	// setup thread handler
	mux.Path("/thread/{id}/").HandlerFunc(m.ServeThread)
	// setup board page handler
	mux.Path("/board/{name}/").HandlerFunc(m.ServeBoardPage)
	// setup posting endpoint
	mux.Path("/post")
	// create captcha
	captchaPrefix := "/captcha/"
	m.captcha = NewCaptchaServer(200, 400, captchaPrefix, m.store)
	// setup captcha endpoint
	m.captcha.SetupRoutes(mux.PathPrefix(captchaPrefix).Subrouter())
}
Beispiel #10
0
func createRoute(router *mux.Router, route Route) {
	r := router.
		Path(route.Path).
		Name(route.Name)

	if route.Headers != nil {
		r.Headers(route.Headers...)
	}

	if route.Queries != nil {
		r.Queries(route.Queries...)
	}

	if route.Schemes != nil {
		r.Schemes(route.Schemes...)
	}

	if route.Methods != nil {
		r.Methods(route.Methods...)
	}

	if route.Host != "" {
		r.Host(route.Host)
	}

	r.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		handler := route.Handler
		for _, middleware := range route.Middleware {
			handler = middleware(handler)
		}
		handler.ServeHTTP(w, r)
	})

}
Beispiel #11
0
func (a *AgentCommand) apiRoutes(r *mux.Router) {
	r.Path("/v1").HandlerFunc(a.indexHandler)
	subver := r.PathPrefix("/v1").Subrouter()
	subver.HandleFunc("/members", a.membersHandler)
	subver.HandleFunc("/leader", a.leaderHandler)

	subver.Path("/jobs").HandlerFunc(a.jobCreateOrUpdateHandler).Methods("POST", "PATCH")
	subver.Path("/jobs").HandlerFunc(a.jobsHandler).Methods("GET")
	sub := subver.PathPrefix("/jobs").Subrouter()
	sub.HandleFunc("/{job}", a.jobGetHandler).Methods("GET")
	sub.HandleFunc("/{job}", a.jobDeleteHandler).Methods("DELETE")
	sub.HandleFunc("/{job}", a.jobRunHandler).Methods("POST")

	subex := subver.PathPrefix("/executions").Subrouter()
	subex.HandleFunc("/{job}", a.executionsHandler).Methods("GET")
}
Beispiel #12
0
func setupAuthApps(authrouter *mux.Router, usermgr UserManager) {
	for _, authkey := range options.AuthKeys {
		authconfig, ok := (*options.AuthConfigs)[authkey.Name]
		if !ok {
			log.Printf("Unknown authenticator \"%s\", skipping", authkey.Name)
			continue
		}
		authconfig.AuthKey = authkey

		var auth Authenticator
		var ex Extractor
		prefix, _ := authrouter.Path("/" + authkey.Name).URL()
		switch authconfig.Extractor.Type {
		case "json":
			ex = NewJSONExtractor(authconfig.Extractor.URL, authconfig.Extractor.Field)
		default:
			log.Printf("Unknown extractor \"%s\", skipping", authconfig.Extractor.Type)
			continue
		}
		switch authconfig.Type {
		case "oauth":
			log.Printf("Enabling %s OAuth on %s with ClientID %s", authkey.Name, prefix.String(), authconfig.AuthKey.ClientID)
			auth = NewOAuthAuthenticator(authkey.Name, &oauth.Config{
				ClientId:     authconfig.AuthKey.ClientID,
				ClientSecret: authconfig.AuthKey.Secret,
				AuthURL:      authconfig.AuthURL,
				TokenURL:     authconfig.TokenURL,
				Scope:        authconfig.Scope,
				RedirectURL:  prefix.String() + "/callback",
			}, ex, usermgr)
		default:
			log.Printf("Unknown authenticator \"%s\", skipping", authconfig.Type)
			continue
		}
		authrouter.PathPrefix("/" + authkey.Name).Handler(
			context.ClearHandler(HandlerList{
				SilentHandler(SessionHandler(options.SessionStore, int(options.SessionTTL/time.Second))),
				http.StripPrefix(prefix.Path, auth),
			}))
	}
	authrouter.Handle("/", authListHandler(options.AuthConfigs))
	authrouter.Path("/logout").Handler(
		context.ClearHandler(HandlerList{
			SilentHandler(SessionHandler(options.SessionStore, int(options.SessionTTL/time.Second))),
			http.HandlerFunc(LogoutHandler),
		}))
}
Beispiel #13
0
// PopulateNamespace adds namespace-specific routes to a router.
// r should be rooted at the root of the Coordinate URL tree, e.g. "/".
func (api *restAPI) PopulateNamespace(r *mux.Router) {
	r.Path("/namespace").Name("namespaces").Handler(&resourceHandler{
		Representation: restdata.NamespaceShort{},
		Context:        api.Context,
		Get:            api.NamespaceList,
		Post:           api.NamespacePost,
	})
	r.Path("/namespace/{namespace}").Name("namespace").Handler(&resourceHandler{
		Representation: restdata.Namespace{},
		Context:        api.Context,
		Get:            api.NamespaceGet,
		Delete:         api.NamespaceDelete,
	})
	sr := r.PathPrefix("/namespace/{namespace}").Subrouter()
	api.PopulateWorkSpec(sr)
	api.PopulateWorker(sr)
}
Beispiel #14
0
func setupPaymentsRoutes(r *mux.Router) {
	client := redis.NewTCPClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	store := &RedisStorage{
		Client: client,
	}
	ph := NewPaymentsHandler(store)

	r.
		Path("/api/payments/{id}").
		Methods("GET").
		HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			vars := mux.Vars(r)
			id := vars["id"]

			p, err := ph.Get(id)
			if err != nil {
				http.Error(w, "Not found", http.StatusNotFound)
				return
			}
			renderAsJson(w, p)
		})

	r.
		Path("/api/payments").
		Methods("POST").
		HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			decoder := json.NewDecoder(r.Body)
			var p Payments
			err := decoder.Decode(&p)
			if err != nil {
				http.Error(w, "Bad data", http.StatusBadRequest)
				return
			}
			p, err = ph.Create(p)
			if err != nil {
				http.Error(w, "Err", http.StatusInternalServerError)
				return
			}
			renderAsJson(w, p)
		})
}
Beispiel #15
0
// SetupRoutes populates the routes for the REST interface
func SetupRoutes(r *mux.Router) {
	// API v1
	r.Path("/api/v1/mailbox/{name}").Handler(httpd.Handler(MailboxListV1)).Name("MailboxListV1").Methods("GET")
	r.Path("/api/v1/mailbox/{name}").Handler(httpd.Handler(MailboxPurgeV1)).Name("MailboxPurgeV1").Methods("DELETE")
	r.Path("/api/v1/mailbox/{name}/{id}").Handler(httpd.Handler(MailboxShowV1)).Name("MailboxShowV1").Methods("GET")
	r.Path("/api/v1/mailbox/{name}/{id}").Handler(httpd.Handler(MailboxDeleteV1)).Name("MailboxDeleteV1").Methods("DELETE")
	r.Path("/api/v1/mailbox/{name}/{id}/source").Handler(httpd.Handler(MailboxSourceV1)).Name("MailboxSourceV1").Methods("GET")
}
Beispiel #16
0
func InitQuestionRoutes(r *mux.Router) *mux.Router {

	//GET
	r.Path("/post/{questionId:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}").Methods("GET").Name(ReadPost)
	r.Path("/questions/{filter:posted-by|answered-by|category}/{val:[A-Za-z0-9]+}").Methods("GET").Name(ReadQuestionsByFilter)
	r.Path("/{postComponent:questions|answers}/{sortedBy:upvotes|edits|date}/{order:desc|asc}/{offset:[0-9]+}").Methods("GET").Name(ReadSortedQuestions)

	//POST
	r.Path("/question/{category:[a-z]+}").Methods("POST").Name(CreateQuestion)

	return r

}
Beispiel #17
0
// Setup sub routes for more efficient routing of requests inside of gorilla mux.
func (f *Fogo) SubRoute(prefix, path string, methods []string, hf FogoHandler) {
	var subRouter *mux.Router
	var ok bool

	subRouter, ok = f.subRoutes[prefix]
	if !ok {
		subRouter = f.router.PathPrefix(prefix).Subrouter()
		f.subRoutes[prefix] = subRouter
	}

	fn := func(w http.ResponseWriter, r *http.Request) {
		f.runRoute(w, r, hf, prefix+path)
	}

	if methods != nil {
		subRouter.Path(path).Methods(methods...).HandlerFunc(fn)
	} else {
		subRouter.Path(path).HandlerFunc(fn)
	}
}
Beispiel #18
0
func InitUserRoutes(r *mux.Router) *mux.Router {

	//GET
	r.Path("/{filter:id|username}/{searchVal:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[a-z0-9]}").Methods("GET").Name(ReadUser)

	//POST
	r.Path("/register").Methods("POST").Name(CreateUser)
	r.Path("/login").Methods("POST").Name(Login)
	r.Path("/logout").Methods("POST").Name(Logout)

	return r

}
Beispiel #19
0
func AddRoutes(router *mux.Router) *mux.Router {
	router.Path("/")

	for acceptHeader, vApi := range acceptVersionMap {
		// Create a subrouter for the header/api version.
		subrouter := router.MatcherFunc(
			acceptOrQueryMatcherFactory(acceptHeader)).Subrouter()

		// Define the path/handler relationships.
		pathHandlerMap := map[string]func(http.ResponseWriter, *http.Request){
			"/json.json":  vApi.JsonHandler,
			"/json2.json": vApi.JsonHandler2,
			"/json3.json": vApi.JsonHandler3,
		}
		// Create a route in the subrouter for each path/handler.
		for path, handler := range pathHandlerMap {
			route := subrouter.HandleFunc(path, handler)
			route.Name(fmt.Sprintf("%s - %s", path, handler))
		}
	}
	return router
}
Beispiel #20
0
// Router adds panel routes to an existing mux.Router.
func UIRouter(theBaseHref string, rt *mux.Router) *mux.Router {
	baseHref = theBaseHref
	rt.Path("/calls").Methods("GET").HandlerFunc(uiCalls).Name(trackUICalls)
	rt.Path("/views").Methods("GET").HandlerFunc(uiViews).Name(trackUIViews)
	rt.Path("/users").Methods("GET").HandlerFunc(uiUsers).Name(trackUIUsers)
	rt.Path("/").Methods("GET").HandlerFunc(uiMain).Name(trackUIMain)

	return rt
}
func CreateObjectServer(router *mux.Router, repository ObjectRepository) *ObjectServer {
	server := &ObjectServer{
		repository: repository,
	}
	server.route = router.Path("/{id}").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		id := vars["id"]

		if id == "" {
			log.Println("bad request: no ID specified")
			http.Error(w, "no ID specified", http.StatusBadRequest)
			return
		}

		object, found := repository.FindObject(id)
		if !found {
			err := fmt.Errorf("id not found: %s", id)
			log.Printf(err.Error())
			http.NotFound(w, req)
			return
		}

		data, err := object.Open()
		if err != nil {
			err := fmt.Sprintf("error opening object %s: %s", id, err)
			log.Printf(err)
			http.Error(w, err, http.StatusInternalServerError)
			return
		}
		defer data.Close()
		log.Printf("loaded object id: %s (%d bytes)", id, object.Size())

		http.ServeContent(w, req, id, object.LastModified(), data)
	})
	return server
}
Beispiel #22
0
func setupPrimaryRouter(r *mux.Router, context *context, enableCors bool) {
	for method, mappings := range routes {
		for route, fct := range mappings {
			log.WithFields(log.Fields{"method": method, "route": route}).Debug("Registering HTTP route")

			localRoute := route
			localFct := fct

			wrap := func(w http.ResponseWriter, r *http.Request) {
				log.WithFields(log.Fields{"method": r.Method, "uri": r.RequestURI}).Debug("HTTP request received")
				if enableCors {
					writeCorsHeaders(w, r)
				}
				context.apiVersion = mux.Vars(r)["version"]
				localFct(context, w, r)
			}
			localMethod := method

			r.Path("/v{version:[0-9]+.[0-9]+}" + localRoute).Methods(localMethod).HandlerFunc(wrap)
			r.Path(localRoute).Methods(localMethod).HandlerFunc(wrap)

			if enableCors {
				optionsMethod := "OPTIONS"
				optionsFct := optionsHandler

				wrap := func(w http.ResponseWriter, r *http.Request) {
					log.WithFields(log.Fields{"method": optionsMethod, "uri": r.RequestURI}).
						Debug("HTTP request received")
					if enableCors {
						writeCorsHeaders(w, r)
					}
					context.apiVersion = mux.Vars(r)["version"]
					optionsFct(context, w, r)
				}

				r.Path("/v{version:[0-9]+.[0-9]+}" + localRoute).
					Methods(optionsMethod).HandlerFunc(wrap)
				r.Path(localRoute).Methods(optionsMethod).
					HandlerFunc(wrap)
			}
		}
	}
}
Beispiel #23
0
func SetRoutes(r *mux.Router) {
	simulate := r.Path("/simulate").Subrouter()
	simulate.Methods("GET").HandlerFunc(SimulateGet)

	people := r.Path("/people").Subrouter()
	people.Methods("GET").HandlerFunc(PeopleGet)
	people.Methods("POST").HandlerFunc(PeoplePost)

	r.Path("/people/new").Methods("GET").HandlerFunc(PeopleGetNew)

	person := r.PathPrefix("/people/{id:[0-9]+}").Subrouter()
	person.Methods("GET").HandlerFunc(PeopleGetOne)
	person.Methods("POST").HandlerFunc(PeoplePostOne)
	person.Methods("DELETE").HandlerFunc(PeoplePostRemove)
	person.Path("/allocations").Methods("GET").HandlerFunc(PeopleAllocateGet)

	r.PathPrefix("/s/").Handler(http.StripPrefix("/s/", http.FileServer(http.Dir("./public"))))
	r.HandleFunc("/", HomeIndex)

	http.Handle("/", r)
}
Beispiel #24
0
// PopulateWorkUnit adds routes to a namespace router to manipulate
// work unit.  r should generally be rooted in a subpath like
// /namespace/{}/work_spec/{}.
func (api *restAPI) PopulateWorkUnit(r *mux.Router) {
	r.Path("/work_unit").Name("workUnits").Handler(&resourceHandler{
		Representation: restdata.WorkUnit{},
		Context:        api.Context,
		Get:            api.WorkUnitsGet,
		Delete:         api.WorkUnitsDelete,
		Post:           api.WorkUnitsPost,
	})
	r.Path("/work_unit/{unit}").Name("workUnit").Handler(&resourceHandler{
		Representation: restdata.WorkUnit{},
		Context:        api.Context,
		Get:            api.WorkUnitGet,
		Put:            api.WorkUnitPut,
	})
	r.Path("/work_unit/{unit}/attempts").Name("workUnitAttempts").Handler(&resourceHandler{
		Representation: restdata.AttemptList{},
		Context:        api.Context,
		Get:            api.WorkUnitAttempts,
	})
	sr := r.PathPrefix("/work_unit/{unit}").Subrouter()
	api.PopulateAttempt(sr)
}
Beispiel #25
0
func (a *AgentCommand) dashboardRoutes(r *mux.Router) {
	r.Path("/dashboard").HandlerFunc(a.dashboardIndexHandler).Methods("GET")
	subui := r.PathPrefix("/dashboard").Subrouter()
	subui.HandleFunc("/jobs", a.dashboardJobsHandler).Methods("GET")
	subui.HandleFunc("/jobs/{job}/executions", a.dashboardExecutionsHandler).Methods("GET")
}
// SetupProtobufV2Paths tells the router which paths the given handler (which should handle v2 protobufs)
// should see
func SetupProtobufV2Paths(r *mux.Router, handler http.Handler) {
	r.Path("/v2/datapoint").Methods("POST").Headers("Content-Type", "application/x-protobuf").Handler(handler)
}
// SetupJSONV2Paths tells the router which paths the given handler (which should handle v2 JSON)
// should see
func SetupJSONV2Paths(r *mux.Router, handler http.Handler) {
	r.Path("/v2/datapoint").Methods("POST").Headers("Content-Type", "application/json").Handler(handler)
	r.Path("/v2/datapoint").Methods("POST").Headers("Content-Type", "").HandlerFunc(invalidContentType)
	r.Path("/v2/datapoint").Methods("POST").Handler(handler)
}
Beispiel #28
0
func (api *restAPI) PopulateAttempt(r *mux.Router) {
	r.Path("/attempt").Name("attempts").Handler(&resourceHandler{
		Representation: restdata.AttemptShort{},
		Context:        api.Context,
	})
	r.Path("/attempt/{worker}/{start}").Name("attempt").Handler(&resourceHandler{
		Representation: restdata.AttemptShort{},
		Context:        api.Context,
		Get:            api.AttemptGet,
	})
	r.Path("/attempt/{worker}/{start}/renew").Name("attemptRenew").Handler(&resourceHandler{
		Representation: restdata.AttemptCompletion{},
		Context:        api.Context,
		Post:           api.AttemptRenew,
	})
	r.Path("/attempt/{worker}/{start}/expire").Name("attemptExpire").Handler(&resourceHandler{
		Representation: restdata.AttemptCompletion{},
		Context:        api.Context,
		Post:           api.AttemptExpire,
	})
	r.Path("/attempt/{worker}/{start}/finish").Name("attemptFinish").Handler(&resourceHandler{
		Representation: restdata.AttemptCompletion{},
		Context:        api.Context,
		Post:           api.AttemptFinish,
	})
	r.Path("/attempt/{worker}/{start}/fail").Name("attemptFail").Handler(&resourceHandler{
		Representation: restdata.AttemptCompletion{},
		Context:        api.Context,
		Post:           api.AttemptFail,
	})
	r.Path("/attempt/{worker}/{start}/retry").Name("attemptRetry").Handler(&resourceHandler{
		Representation: restdata.AttemptCompletion{},
		Context:        api.Context,
		Post:           api.AttemptRetry,
	})
}
Beispiel #29
0
// New initalizes a new auth router.
func New(r *mux.Router) {
	r.Path("/auth").Methods("POST").HandlerFunc(register)
	r.Path("/auth/login").Methods("POST").HandlerFunc(login)
	r.Path("/auth/user").Methods("GET").HandlerFunc(CheckAuth(getUser))
	r.Path("/auth/user").Methods("POST").HandlerFunc(CheckAuth(updateUser))
}
// SetupCollectdPaths tells the router which paths the given handler (which should handle collectd json)
// should see
func SetupCollectdPaths(r *mux.Router, handler http.Handler) {
	r.Path("/v1/collectd").Methods("POST").Headers("Content-Type", "application/json").Handler(handler)
	r.Path("/v1/collectd").Methods("POST").Headers("Content-Type", "").HandlerFunc(invalidContentType)
}