Exemplo n.º 1
0
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")
}
Exemplo n.º 2
0
// 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, "")
				}
			}
		}
	})
}
Exemplo n.º 3
0
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")
}
Exemplo n.º 4
0
func AddStatusHandler(router *mux.Router) {
	router.HandleFunc("/status.txt", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Fprint(rw, "alive")
		return
	})
	return
}
Exemplo n.º 5
0
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)
	}
}
Exemplo n.º 6
0
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
}
Exemplo n.º 7
0
// 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())
		}
	}
}
Exemplo n.º 8
0
func Register(rtr *mux.Router, bus *eventbus.EventBus) {
	rtr.HandleFunc("/ws", upgradeHandler).Methods("GET")
	bus.RegisterHandler(serviceStateChanged)
	bus.RegisterHandler(viewStateChanged)

	go h.run()
}
Exemplo n.º 9
0
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)
}
Exemplo n.º 10
0
// 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()
}
Exemplo n.º 11
0
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")
}
Exemplo n.º 12
0
func Home(r *mux.Router) {

	//home
	r.HandleFunc("/home", func(w http.ResponseWriter, req *http.Request) {
		view(w, "index", "Eu sou a mensagem exemplo")
	})
}
Exemplo n.º 13
0
// 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)
	}
}
Exemplo n.º 14
0
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")
}
Exemplo n.º 15
0
// 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)
}
Exemplo n.º 16
0
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
}
Exemplo n.º 17
0
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
}
Exemplo n.º 18
0
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)
}
Exemplo n.º 19
0
// 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)
}
Exemplo n.º 20
0
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
}
func setupRouters(ctx *RouterContext.RouterContext, router *mux.Router, parentMiddleWare []HttpHandlerFunc, routeDefinitions []*RouteDefinition) {
	if len(routeDefinitions) == 0 {
		return
	}

	for _, rh := range routeDefinitions {
		var routerToUse *mux.Router
		if rh.prefix != "" {
			routerToUse = router.PathPrefix(rh.prefix).Subrouter()
		} else {
			routerToUse = router
		}

		combinedMiddleWareHandlers := []HttpHandlerFunc{}
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, parentMiddleWare...)
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, rh.middlewares...)

		for _, singleRouteDefinition := range rh.routeDefinitions {
			for method, h := range GetIRouteControllers(singleRouteDefinition) {
				muxRoute := routerToUse.Handle(singleRouteDefinition.GetPathPart(), newNegroniMiddleware(ctx, combinedMiddleWareHandlers, h))
				muxRoute.Methods(method)
			}
		}

		setupRouters(ctx, routerToUse, combinedMiddleWareHandlers, rh.subRoutes)
	}
}
Exemplo n.º 22
0
func fileServeRoutes(router *mux.Router) {
	controller := controllers.NewFileServeController()

	router.Handle("/image/{folder}/{file}", negroni.New(
		negroni.HandlerFunc(controller.GetImage),
	)).Methods("GET")
}
Exemplo n.º 23
0
//Register - registers an API Call with the router
func (call *APICall) Register(router *mux.Router) {
	log.Println("Call: ", call)
	router.Methods(call.Methods...).
		Name(call.Name).
		Path(call.Path).
		HandlerFunc(call.HandlerFunc)
}
Exemplo n.º 24
0
func InitLicense(r *mux.Router) {
	l4g.Debug(utils.T("api.license.init.debug"))

	sr := r.PathPrefix("/license").Subrouter()
	sr.Handle("/add", ApiAdminSystemRequired(addLicense)).Methods("POST")
	sr.Handle("/remove", ApiAdminSystemRequired(removeLicense)).Methods("POST")
}
Exemplo n.º 25
0
// AddPingRoute adds an optimized ping route to the given router
func AddPingRoute(router *mux.Router) *mux.Route {
	return router.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"pong":true}`))
	}).Methods("GET", "HEAD", "OPTIONS")
}
Exemplo n.º 26
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
}
Exemplo n.º 27
0
func wouldMatch(router *mux.Router, rq *http.Request, method string) bool {
	savedMethod := rq.Method
	rq.Method = method
	defer func() { rq.Method = savedMethod }()
	var matchInfo mux.RouteMatch
	return router.Match(rq, &matchInfo)
}
Exemplo n.º 28
0
// registerWebRouter - registers web router for serving minio browser.
func registerWebRouter(mux *router.Router, web *webAPIHandlers) {
	// Initialize a new json2 codec.
	codec := json2.NewCodec()

	// Minio browser router.
	webBrowserRouter := mux.NewRoute().PathPrefix(reservedBucket).Subrouter()

	// Initialize json rpc handlers.
	webRPC := jsonrpc.NewServer()
	webRPC.RegisterCodec(codec, "application/json")
	webRPC.RegisterCodec(codec, "application/json; charset=UTF-8")
	webRPC.RegisterService(web, "Web")

	// RPC handler at URI - /minio/webrpc
	webBrowserRouter.Methods("POST").Path("/webrpc").Handler(webRPC)
	webBrowserRouter.Methods("PUT").Path("/upload/{bucket}/{object:.+}").HandlerFunc(web.Upload)
	webBrowserRouter.Methods("GET").Path("/download/{bucket}/{object:.+}").Queries("token", "{token:.*}").HandlerFunc(web.Download)

	// Add compression for assets.
	compressedAssets := handlers.CompressHandler(http.StripPrefix(reservedBucket, http.FileServer(assetFS())))

	// Serve javascript files and favicon from assets.
	webBrowserRouter.Path(fmt.Sprintf("/{assets:[^/]+.js|%s}", specialAssets)).Handler(compressedAssets)

	// Serve index.html for rest of the requests.
	webBrowserRouter.Path("/{index:.*}").Handler(indexHandler{http.StripPrefix(reservedBucket, http.FileServer(assetFS()))})
}
Exemplo n.º 29
0
func setupRouters(router *mux.Router, parentMiddleWare []http.HandlerFunc, routers []*Router) {
	if len(routers) == 0 {
		return
	}

	for _, rd := range routers {
		combinedMiddleWareHandlers := []http.HandlerFunc{}
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, parentMiddleWare...)
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, rd.middlewares...)

		panicOnZeroMethods := len(rd.subRouters) == 0 //Panic if we have no controller methods and also no subrouters
		for method, handler := range GetControllerMethods(rd.controller, panicOnZeroMethods) {
			for _, urlPart := range rd.urlParts {
				muxRoute := router.Handle(urlPart, newNegroniMiddleware(combinedMiddleWareHandlers, handler))
				muxRoute.Methods(method)
			}
		}

		if len(rd.urlParts) == 0 {
			setupRouters(router, combinedMiddleWareHandlers, rd.subRouters)
			continue
		}

		for _, urlPart := range rd.urlParts {
			var subRouterToUse *mux.Router
			if urlPart != "" {
				subRouterToUse = router.PathPrefix(urlPart).Subrouter()
			} else {
				subRouterToUse = router
			}
			setupRouters(subRouterToUse, combinedMiddleWareHandlers, rd.subRouters)
		}
	}
}
func registerIdentityTenants(s *CollectorSuite, r *mux.Router) {
	r.HandleFunc("/v2.0/tenants", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("X-Auth-Token", s.Token)

		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)

		fmt.Fprintf(w, `
			{
				"tenants": [
					{
						"description": "Test tenat",
						"enabled": true,
						"id": "%s",
						"name": "%s"
					},
					{
						"description": "admin tenant",
						"enabled": true,
						"id": "%s",
						"name": "%s"
					}
				],
				"tenants_links": []
			}
		`, s.Tenant1ID, s.Tenant1Name, s.Tenant2ID, s.Tenant2Name)
	}).Methods("GET")
}