Esempio n. 1
0
// Setup all routes for API v2
func setupApi2(router *httprouter.Router) {
	router.GET("/api/v2", APIv2.ApiIndexVersion)

	// Public Statistics
	router.GET("/api/v2/websites", APIv2.ApiWebsites)
	router.GET("/api/v2/websites/:url/status", APIv2.ApiWebsitesStatus)
	router.GET("/api/v2/websites/:url/results", APIv2.ApiWebsitesResults)

	// Authentication
	router.POST("/api/v2/auth/login", APIv2.ApiAuthLogin)
	router.GET("/api/v2/auth/logout", APIv2.ApiAuthLogout)

	// Settings
	router.PUT("/api/v2/settings/password", APIv2.ApiSettingsPassword)
	router.PUT("/api/v2/settings/interval", APIv2.ApiSettingsInterval)

	// Website Management
	router.POST("/api/v2/websites/:url", APIv2.ApiWebsitesAdd)
	router.PUT("/api/v2/websites/:url", APIv2.ApiWebsitesEdit)
	router.DELETE("/api/v2/websites/:url", APIv2.ApiWebsitesDelete)
	router.PUT("/api/v2/websites/:url/enabled", APIv2.ApiWebsitesEnabled)
	router.PUT("/api/v2/websites/:url/visibility", APIv2.ApiWebsitesVisibility)
	router.GET("/api/v2/websites/:url/notifications", APIv2.ApiWebsitesGetNotifications)
	router.PUT("/api/v2/websites/:url/notifications", APIv2.ApiWebsitePutNotifications)
	router.GET("/api/v2/websites/:url/check", APIv2.ApiWebsiteCheck)
}
Esempio n. 2
0
func (c *streamController) Register(router *httprouter.Router) {
	router.PUT("/streams", basicAuth(c.handle(c.addToStream), c.authConfig))
	router.POST("/streams/coalesce", basicAuth(c.handle(c.coalesceStreams), c.authConfig))
	router.GET("/stream/:id", basicAuth(c.handle(c.getStream), c.authConfig))

	log.Debug("Routes Registered")
}
Esempio n. 3
0
func (e profileEndpoint) Register(mux *httprouter.Router) {
	mux.GET("/profile/:userId/displayname", jsonHandler(e.getDisplayName))
	mux.PUT("/profile/:userId/displayname", jsonHandler(e.setDisplayName))
	mux.GET("/profile/:userId/avatar_url", jsonHandler(e.getAvatarUrl))
	mux.PUT("/profile/:userId/avatar_url", jsonHandler(e.setAvatarUrl))
	mux.GET("/profile/:userId", jsonHandler(e.getProfile))
}
Esempio n. 4
0
func (c *streamController) Register(router *httprouter.Router) {
	router.PUT("/streams", basicAuth(timeRequest(c.handle(c.addToStream), addToStreamTimer), c.authConfig))
	router.DELETE("/streams", basicAuth(timeRequest(c.handle(c.removeFromStream), removeFromStreamTimer), c.authConfig))
	router.POST("/streams/coalesce", basicAuth(timeRequest(c.handle(c.coalesceStreams), coalesceTimer), c.authConfig))
	router.GET("/stream/:id", basicAuth(timeRequest(c.handle(c.getStream), getStreamTimer), c.authConfig))

	log.Debug("Routes Registered")
}
Esempio n. 5
0
func (h *Handler) SetRoutes(r *httprouter.Router) {
	r.POST("/keys/:set", h.Create)
	r.PUT("/keys/:set", h.UpdateKeySet)
	r.GET("/keys/:set", h.GetKeySet)
	r.DELETE("/keys/:set", h.DeleteKeySet)

	r.PUT("/keys/:set/:key", h.UpdateKey)
	r.GET("/keys/:set/:key", h.GetKey)
	r.DELETE("/keys/:set/:key", h.DeleteKey)

}
Esempio n. 6
0
func (api *HTTPAPI) RegisterRoutes(r *httprouter.Router) {
	r.POST("/storage/providers", api.CreateProvider)
	r.POST("/storage/providers/:provider_id/volumes", api.Create)
	r.GET("/storage/volumes", api.List)
	r.GET("/storage/volumes/:volume_id", api.Inspect)
	r.DELETE("/storage/volumes/:volume_id", api.Destroy)
	r.PUT("/storage/volumes/:volume_id/snapshot", api.Snapshot)
	// takes host and volID parameters, triggers a send on the remote host and give it a list of snaps already here, and pipes it into recv
	r.POST("/storage/volumes/:volume_id/pull_snapshot", api.Pull)
	// responds with a snapshot stream binary.  only works on snapshots, takes 'haves' parameters, usually called by a node that's servicing a 'pull_snapshot' request
	r.GET("/storage/volumes/:volume_id/send", api.Send)
}
Esempio n. 7
0
// addUsersHandlers add Users handler to router
func addUsersHandlers(router *httprouter.Router) {
	// add user
	router.POST("/users/:user", wrapHandler(usersAdd))

	// get all users
	router.GET("/users", wrapHandler(usersGetAll))

	// get one user
	router.GET("/users/:user", wrapHandler(usersGetOne))

	// del an user
	router.DELETE("/users/:user", wrapHandler(usersDel))

	// change user password
	router.PUT("/users/:user", wrapHandler(usersUpdate))
}
Esempio n. 8
0
func (h *jobAPI) RegisterRoutes(r *httprouter.Router) error {
	r.GET("/host/jobs", h.ListJobs)
	r.GET("/host/jobs/:id", h.GetJob)
	r.PUT("/host/jobs/:id", h.AddJob)
	r.DELETE("/host/jobs/:id", h.StopJob)
	r.PUT("/host/jobs/:id/signal/:signal", h.SignalJob)
	r.POST("/host/pull/images", h.PullImages)
	r.POST("/host/pull/binaries", h.PullBinariesAndConfig)
	r.POST("/host/discoverd", h.ConfigureDiscoverd)
	r.POST("/host/network", h.ConfigureNetworking)
	r.GET("/host/status", h.GetStatus)
	r.POST("/host/resource-check", h.ResourceCheck)
	r.POST("/host/update", h.Update)
	r.POST("/host/tags", h.UpdateTags)
	return nil
}
Esempio n. 9
0
// setupHTTP attaches all the needed handlers to provide the HTTP API.
func (m *Manta) SetupHTTP(mux *httprouter.Router) {

	baseRoute := "/" + m.ServiceInstance.UserAccount
	mux.NotFound = ErrNotFound
	mux.MethodNotAllowed = ErrNotAllowed
	mux.RedirectFixedPath = true
	mux.RedirectTrailingSlash = true
	mux.HandleMethodNotAllowed = true

	// this particular route can't be handled by httprouter correctly due to its
	// handling of positional parameters but we can't just pass in ErrNotAllowed
	// either because it's the wrong type
	handleNotAllowed := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		w.WriteHeader(http.StatusMethodNotAllowed)
		w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
		w.Write([]byte("Method is not allowed"))
	}
	mux.POST(baseRoute+"/stor", handleNotAllowed)

	// storage APIs
	// PutSnapLink and PutMetaData have the same route spec as other routes
	// in this group, which isn't permitted by httprouter. We pick up the
	// correct path in the handler
	mux.PUT(baseRoute+"/stor/:dir", m.handler((*Manta).handleStorage))         // PutDirectory
	mux.GET(baseRoute+"/stor/:dir", m.handler((*Manta).handleStorage))         // ListDirectory
	mux.DELETE(baseRoute+"/stor/:dir", m.handler((*Manta).handleStorage))      // DeleteDirectory
	mux.PUT(baseRoute+"/stor/:dir/:obj", m.handler((*Manta).handleStorage))    // PutObject
	mux.GET(baseRoute+"/stor/:dir/:obj", m.handler((*Manta).handleStorage))    // GetObject
	mux.DELETE(baseRoute+"/stor/:dir/:obj", m.handler((*Manta).handleStorage)) // DeleteObject

	// job APIs
	mux.POST(baseRoute+"/jobs", m.handler((*Manta).handleJobs))                 // CreateJob
	mux.POST(baseRoute+"/jobs/:id/live/in", m.handler((*Manta).handleJobs))     // AddJobInputs
	mux.POST(baseRoute+"/jobs/:id/live/in/end", m.handler((*Manta).handleJobs)) // EndJobInput
	mux.POST(baseRoute+"/jobs/:id/live/cancel", m.handler((*Manta).handleJobs)) // CancelJob
	mux.GET(baseRoute+"/jobs", m.handler((*Manta).handleJobs))                  // ListJobs
	mux.GET(baseRoute+"/jobs/:id/live/status", m.handler((*Manta).handleJobs))  // GetJob
	mux.GET(baseRoute+"/jobs/:id/live/out", m.handler((*Manta).handleJobs))     // GetJobOutput
	mux.GET(baseRoute+"/jobs/:id/live/in", m.handler((*Manta).handleJobs))      // GetJobInput
	mux.GET(baseRoute+"/jobs/:id/live/fail", m.handler((*Manta).handleJobs))    // GetJobFailures
	mux.GET(baseRoute+"/jobs/:id/live/err", m.handler((*Manta).handleJobs))     // GetJobErrors
}
Esempio n. 10
0
func (self *CommandModule) LoadRoutes(router *httprouter.Router) error {
	router.GET(`/api/commands/list`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		util.Respond(w, http.StatusOK, self.Commands, nil)
	})

	router.PUT(`/api/commands/run/:name`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		name := params.ByName(`name`)

		if command, ok := self.Commands[name]; ok {
			if results, err := command.Execute(); err == nil {
				util.Respond(w, http.StatusOK, results, nil)
			} else {
				util.Respond(w, http.StatusOK, results, nil)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Cannot find a command called '%s'", name))
		}
	})

	return nil
}
Esempio n. 11
0
func setup(router *httprouter.Router) {
	router.GET("/api/user", controller.UserGet)
	router.GET("/api/user/:id", controller.UserGet)
	router.GET("/api/redis/user/:id", controller.RedisUserGet)
	router.GET("/api/redis/user", controller.RedisUserGet)
	router.PUT("/api/user", controller.UserUpsert)
	router.PUT("/api/user/:id", controller.UserUpsert)
	router.PUT("/api/redis/user/:id", controller.RedisUserWrite)
	router.DELETE("/api/user", controller.UserDelete)
	router.DELETE("/api/user/:id", controller.UserDelete)
	router.PATCH("/api/user/:id", controller.UserUpdate)

	// TOTEC
	router.GET("/api/musics", controller.MusicGet)
	router.GET("/api/musics/:id", controller.MusicGet)
	router.POST("/api/musics", controller.MusicUpsert)
	router.PUT("/api/musics/:id", controller.MusicUpsert)
	router.DELETE("/api/musics/:id", controller.MusicDelete)

	router.POST("/api/musics/:id/play", controller.HistoryUpsert)
}
Esempio n. 12
0
func (e roomsEndpoint) Register(mux *httprouter.Router) {
	mux.POST("/rooms/:roomId/send/:eventType", jsonHandler(e.sendMessage))
	mux.PUT("/rooms/:roomId/send/:eventType/:txn", jsonHandler(e.sendMessage))
	mux.PUT("/rooms/:roomId/state/:eventType", e.handlePutState)
	mux.PUT("/rooms/:roomId/state/:eventType/:stateKey", e.handlePutState)
	// mux.GET("/rooms/:roomId/state/:eventType", jsonHandler(dummy))
	// mux.GET("/rooms/:roomId/state/:eventType/:stateKey", jsonHandler(dummy))
	mux.POST("/rooms/:roomId/invite", jsonHandler(e.doInvite))
	mux.POST("/rooms/:roomId/kick", jsonHandler(e.doKick))
	mux.POST("/rooms/:roomId/ban", jsonHandler(e.doBan))
	mux.POST("/rooms/:roomId/join", jsonHandler(e.doJoin))
	mux.POST("/rooms/:roomId/knock", jsonHandler(e.doKnock))
	mux.POST("/rooms/:roomId/leave", jsonHandler(e.doLeave))
	mux.GET("/rooms/:roomId/messages", jsonHandler(e.getMessages))
	// mux.GET("/rooms/:roomId/members", jsonHandler(dummy))
	// mux.GET("/rooms/:roomId/state", jsonHandler(dummy))
	// mux.PUT("/rooms/:roomId/typing/:userId", jsonHandler(dummy))
	mux.GET("/rooms/:roomId/initialSync", jsonHandler(e.doInitialSync))
	mux.POST("/join/:roomAliasOrId", jsonHandler(e.doWildcardJoin))
	mux.POST("/createRoom", jsonHandler(e.createRoom))
}
Esempio n. 13
0
// RegisterRouter registers a router onto the Server.
func (s *Server) RegisterRouter(router *httprouter.Router) {
	router.GET("/ping", s.ping)

	router.GET("/customer", s.getCustomers)
	router.POST("/customer", s.createCustomer)
	router.GET("/customer/:customerID", s.getCustomer)
	router.PUT("/customer/:customerID", s.updateCustomer)
	router.DELETE("/customer/:customerID", s.deleteCustomer)

	router.GET("/product", s.getProducts)
	router.POST("/product", s.createProduct)
	router.GET("/product/:productID", s.getProduct)
	router.PUT("/product/:productID", s.updateProduct)
	router.DELETE("/product/:productID", s.deleteProduct)

	router.GET("/order", s.getOrders)
	router.POST("/order", s.createOrder)
	router.GET("/order/:orderID", s.getOrder)
	router.PUT("/order/:orderID", s.updateOrder)
	router.DELETE("/order/:orderID", s.deleteOrder)
	router.POST("/order/:orderID/product", s.addProductToOrder)
}
Esempio n. 14
0
func PUT(r *httprouter.Router, path string, handler Handler) {
	r.PUT(path, handle(handler))
}
Esempio n. 15
0
func (e eventsEndpoint) Register(mux *httprouter.Router) {
	mux.GET("/events", jsonHandler(e.getEvents))
	mux.PUT("/events/:eventId", jsonHandler(e.getSingleEvent))
	mux.GET("/initialSync", jsonHandler(e.getInitialSync))
	mux.PUT("/publicRooms", jsonHandler(e.getPublicRooms))
}
Esempio n. 16
0
func (self *SoundctlModule) LoadRoutes(router *httprouter.Router) error {
	router.GET(`/api/soundctl/backends`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		keys := make([]string, 0)

		for key, _ := range self.Backends {
			keys = append(keys, key)
		}

		util.Respond(w, http.StatusOK, keys, nil)
	})

	router.GET(`/api/soundctl/backends/:name`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		name := params.ByName(`name`)

		if backend, ok := self.Backends[name]; ok {
			util.Respond(w, http.StatusOK, backend, nil)
		} else {
			util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Unable to locate backend '%s'", name))
		}
	})

	router.GET(`/api/soundctl/backends/:name/outputs/:output`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			util.Respond(w, http.StatusOK, output, nil)
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	router.GET(`/api/soundctl/backends/:name/outputs-property/:key/:value`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		name := params.ByName(`name`)
		propName := params.ByName(`key`)
		propValue := params.ByName(`value`)

		if backend, ok := self.Backends[name]; ok {
			if outputs := backend.GetOutputsByProperty(propName, propValue); len(outputs) > 0 {
				util.Respond(w, http.StatusOK, outputs, nil)
			} else {
				util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Unable to locate any outputs with property %s=%s on backend '%s'", propName, propValue, name))
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Unable to locate backend '%s'", name))
		}
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/set-default`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/mute`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			if err := output.Mute(); err == nil {
				util.Respond(w, http.StatusNoContent, nil, nil)
			} else {
				util.Respond(w, http.StatusInternalServerError, nil, err)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/unmute`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			if err := output.Unmute(); err == nil {
				util.Respond(w, http.StatusNoContent, nil, nil)
			} else {
				util.Respond(w, http.StatusInternalServerError, nil, err)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/toggle`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			if err := output.ToggleMute(); err == nil {
				util.Respond(w, http.StatusNoContent, nil, nil)
			} else {
				util.Respond(w, http.StatusInternalServerError, nil, err)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/volume/:factor`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			if v, err := stringutil.ConvertToFloat(params.ByName(`factor`)); err == nil {
				if err := output.SetVolume(v); err == nil {
					util.Respond(w, http.StatusNoContent, nil, nil)
				} else {
					util.Respond(w, http.StatusInternalServerError, nil, err)
				}
			} else {
				util.Respond(w, http.StatusBadRequest, nil, err)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/volume-up/:factor`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			if v, err := stringutil.ConvertToFloat(params.ByName(`factor`)); err == nil {
				if err := output.IncreaseVolume(v); err == nil {
					util.Respond(w, http.StatusNoContent, nil, nil)
				} else {
					util.Respond(w, http.StatusInternalServerError, nil, err)
				}
			} else {
				util.Respond(w, http.StatusBadRequest, nil, err)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	router.PUT(`/api/soundctl/backends/:name/outputs/:output/volume-down/:factor`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if output, err := self.getNamedOutput(params.ByName(`name`), params.ByName(`output`)); err == nil {
			if v, err := stringutil.ConvertToFloat(params.ByName(`factor`)); err == nil {
				if err := output.DecreaseVolume(v); err == nil {
					util.Respond(w, http.StatusNoContent, nil, nil)
				} else {
					util.Respond(w, http.StatusInternalServerError, nil, err)
				}
			} else {
				util.Respond(w, http.StatusBadRequest, nil, err)
			}
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}
	})

	return nil
}
Esempio n. 17
0
// Setup all routes for API v1
func setupApi1(router *httprouter.Router) {
	router.GET("/api/v1/*all", APIv1.ApiIndexVersion)
	router.POST("/api/v1/*all", APIv1.ApiIndexVersion)
	router.PUT("/api/v1/*all", APIv1.ApiIndexVersion)
	router.DELETE("/api/v1/*all", APIv1.ApiIndexVersion)
}
Esempio n. 18
0
func (e presenceEndpoint) Register(mux *httprouter.Router) {
	mux.GET("/presence/:userId/status", jsonHandler(e.getStatus))
	mux.PUT("/presence/:userId/status", jsonHandler(e.setStatus))
}
Esempio n. 19
0
// SetupHTTP attaches all the needed handlers to provide the HTTP API.
func (c *CloudAPI) SetupHTTP(mux *httprouter.Router) {
	baseRoute := "/" + c.ServiceInstance.UserAccount

	mux.NotFound = NotFound{}
	mux.MethodNotAllowed = MethodNotAllowed{}

	// keys
	keysRoute := baseRoute + "/keys"
	mux.GET(keysRoute, c.handler((*CloudAPI).handleListKeys))
	mux.POST(keysRoute, c.handler((*CloudAPI).handleCreateKey))

	// key
	keyRoute := keysRoute + "/:id"
	mux.GET(keyRoute, c.handler((*CloudAPI).handleGetKey))
	mux.DELETE(keyRoute, c.handler((*CloudAPI).handleDeleteKey))

	// images
	imagesRoute := baseRoute + "/images"
	mux.GET(imagesRoute, c.handler((*CloudAPI).handleListImages))

	// image
	imageRoute := imagesRoute + "/:id"
	mux.GET(imageRoute, c.handler((*CloudAPI).handleGetImage))
	mux.POST(imageRoute, c.handler((*CloudAPI).handleCreateImageFromMachine))
	mux.DELETE(imageRoute, c.handler((*CloudAPI).handleDeleteImage))

	// packages
	packagesRoute := baseRoute + "/packages"
	mux.GET(packagesRoute, c.handler((*CloudAPI).handleListPackages))

	// package
	packageRoute := packagesRoute + "/:id"
	mux.GET(packageRoute, c.handler((*CloudAPI).handleGetPackage))

	// machines
	machinesRoute := baseRoute + "/machines"
	mux.GET(machinesRoute, c.handler((*CloudAPI).handleListMachines))
	mux.HEAD(machinesRoute, c.handler((*CloudAPI).handleCountMachines))
	mux.POST(machinesRoute, c.handler((*CloudAPI).handleCreateMachine))

	// machine
	machineRoute := machinesRoute + "/:id"
	mux.GET(machineRoute, c.handler((*CloudAPI).handleGetMachine))
	mux.POST(machineRoute, c.handler((*CloudAPI).handleUpdateMachine))
	mux.DELETE(machineRoute, c.handler((*CloudAPI).handleDeleteMachine))

	// machine metadata
	machineMetadataRoute := machineRoute + "/metadata"
	mux.GET(machineMetadataRoute, c.handler((*CloudAPI).handleGetMachineMetadata))
	mux.POST(machineMetadataRoute, c.handler((*CloudAPI).handleUpdateMachineMetadata))
	mux.DELETE(machineMetadataRoute, c.handler((*CloudAPI).handleDeleteAllMachineMetadata))

	// machine metadata (individual key)
	machineMetadataKeyRoute := machineMetadataRoute + "/:key"
	mux.DELETE(machineMetadataKeyRoute, c.handler((*CloudAPI).handleDeleteMachineMetadata))

	// machine tags
	machineTagsRoute := machineRoute + "/tags"
	mux.GET(machineTagsRoute, c.handler((*CloudAPI).handleListMachineTags))
	mux.POST(machineTagsRoute, c.handler((*CloudAPI).handleAddMachineTags))
	mux.PUT(machineTagsRoute, c.handler((*CloudAPI).handleReplaceMachineTags))
	mux.DELETE(machineTagsRoute, c.handler((*CloudAPI).handleDeleteMachineTags))

	// machine tag
	machineTagRoute := machineTagsRoute + "/:tag"
	mux.GET(machineTagRoute, c.handler((*CloudAPI).handleGetMachineTag))
	mux.DELETE(machineTagRoute, c.handler((*CloudAPI).handleDeleteMachineTag))

	// machine firewall rules
	machineFWRulesRoute := machineRoute + "/fwrules"
	mux.GET(machineFWRulesRoute, c.handler((*CloudAPI).handleMachineFirewallRules))

	// machine NICs
	machineNICsRoute := machineRoute + "/nics"
	mux.GET(machineNICsRoute, c.handler((*CloudAPI).handleListNICs))
	mux.POST(machineNICsRoute, c.handler((*CloudAPI).handleAddNIC))

	// machine NIC
	machineNICRoute := machineNICsRoute + "/:mac"
	mux.GET(machineNICRoute, c.handler((*CloudAPI).handleGetNIC))
	mux.DELETE(machineNICRoute, c.handler((*CloudAPI).handleRemoveNIC))

	// firewall rules
	firewallRulesRoute := baseRoute + "/fwrules"
	mux.GET(firewallRulesRoute, c.handler((*CloudAPI).handleListFirewallRules))
	mux.POST(firewallRulesRoute, c.handler((*CloudAPI).handleCreateFirewallRule))

	// firewall rule
	firewallRuleRoute := firewallRulesRoute + "/:id"
	mux.GET(firewallRuleRoute, c.handler((*CloudAPI).handleGetFirewallRule))
	mux.POST(firewallRuleRoute, c.handler((*CloudAPI).handleUpdateFirewallRule))
	mux.DELETE(firewallRuleRoute, c.handler((*CloudAPI).handleDeleteFirewallRule))
	mux.POST(firewallRuleRoute+"/enable", c.handler((*CloudAPI).handleEnableFirewallRule))
	mux.POST(firewallRuleRoute+"/disable", c.handler((*CloudAPI).handleDisableFirewallRule))

	// networks
	networksRoute := baseRoute + "/networks"
	mux.GET(networksRoute, c.handler((*CloudAPI).handleListNetworks))

	// network
	networkRoute := networksRoute + "/:id"
	mux.GET(networkRoute, c.handler((*CloudAPI).handleGetNetwork))

	// fabric VLANs
	fabricVLANsRoute := baseRoute + "/fabrics/:fabric/vlans"
	mux.GET(fabricVLANsRoute, c.handler((*CloudAPI).handleListFabricVLANs))
	mux.POST(fabricVLANsRoute, c.handler((*CloudAPI).handleCreateFabricVLAN))

	// fabric VLAN
	fabricVLANRoute := fabricVLANsRoute + "/:id"
	mux.GET(fabricVLANRoute, c.handler((*CloudAPI).handleGetFabricVLAN))
	mux.PUT(fabricVLANRoute, c.handler((*CloudAPI).handleUpdateFabricVLAN))
	mux.DELETE(fabricVLANRoute, c.handler((*CloudAPI).handleDeleteFabricVLAN))

	// fabric VLAN networks
	fabricVLANNetworksRoute := fabricVLANRoute + "/networks"
	mux.GET(fabricVLANNetworksRoute, c.handler((*CloudAPI).handleListFabricNetworks))
	mux.POST(fabricVLANNetworksRoute, c.handler((*CloudAPI).handleCreateFabricNetwork))

	// fabric VLAN network
	fabricVLANNetworkRoute := fabricVLANNetworksRoute + "/:network"
	mux.GET(fabricVLANNetworkRoute, c.handler((*CloudAPI).handleGetFabricNetwork))
	mux.DELETE(fabricVLANNetworkRoute, c.handler((*CloudAPI).handleDeleteFabricNetwork))

	// services
	servicesRoute := baseRoute + "/services"
	mux.GET(servicesRoute, c.handler((*CloudAPI).handleGetServices))
}
Esempio n. 20
0
func (self *SessionModule) LoadRoutes(router *httprouter.Router) error {
	router.GET(`/api/session/workspaces`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if workspaces, err := self.GetAllWorkspaces(); err == nil {
			util.Respond(w, http.StatusOK, workspaces, nil)
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.GET(`/api/session/workspaces/current`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if workspaces, err := self.GetAllWorkspaces(); err == nil {
			for _, workspace := range workspaces {
				if workspace.IsCurrent {
					util.Respond(w, http.StatusOK, workspace, nil)
					return
				}
			}

			util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Current workspace not found"))
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.GET(`/api/session/windows`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if windows, err := self.GetAllWindows(); err == nil {
			for i, _ := range windows {
				windows[i].IconUri = fmt.Sprintf("/api/session/windows/%d/icon", windows[i].ID)
			}

			util.Respond(w, http.StatusOK, windows, nil)
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.GET(`/api/session/windows/:id`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if window, err := self.GetWindow(params.ByName(`id`)); err == nil {
			window.IconUri = fmt.Sprintf("/api/session/windows/%s/icon", params.ByName(`id`))

			util.Respond(w, http.StatusOK, window, nil)
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.GET(`/api/session/windows/:id/icon`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		var buffer bytes.Buffer
		width := uint(16)
		height := uint(16)

		if w := req.URL.Query().Get(`w`); w != `` {
			if value, err := stringutil.ConvertToInteger(w); err == nil {
				width = uint(value)
			}
		}

		if h := req.URL.Query().Get(`h`); h != `` {
			if value, err := stringutil.ConvertToInteger(h); err == nil {
				height = uint(value)
			}
		}

		if height != width {
			height = width
		}

		if err := self.WriteWindowIcon(params.ByName(`id`), width, height, &buffer); err == nil {
			w.Header().Set(`Content-Type`, `image/png`)
			w.Write(buffer.Bytes())
			return
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.GET(`/api/session/windows/:id/image`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		var buffer bytes.Buffer

		if err := self.WriteWindowImage(params.ByName(`id`), &buffer); err == nil {
			w.Header().Set(`Content-Type`, `image/png`)
			w.Write(buffer.Bytes())
			return
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.PUT(`/api/session/windows/:id/do/:action`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		var err error
		id := params.ByName(`id`)

		switch params.ByName(`action`) {
		case `maximize`:
			err = self.MaximizeWindow(id)

		case `max-x`:
			err = self.MaximizeWindowHorizontal(id)

		case `max-y`:
			err = self.MaximizeWindowVertical(id)

		case `minimize`:
			err = self.MinimizeWindow(id)

		case `restore`:
			err = self.RestoreWindow(id)

		case `hide`:
			err = self.HideWindow(id)

		case `show`:
			err = self.ShowWindow(id)

		case `raise`:
			err = self.RaiseWindow(id)

		default:
			util.Respond(w, http.StatusBadRequest, nil, fmt.Errorf("Unknown action '%s'", params.ByName(`action`)))
			return
		}

		if err == nil {
			util.Respond(w, http.StatusAccepted, nil, nil)
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.PUT(`/api/session/windows/:id/move/:x/:y`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		id := params.ByName(`id`)
		var x, y int

		if value, err := stringutil.ConvertToInteger(params.ByName(`x`)); err == nil {
			x = int(value)
		} else {
			util.Respond(w, http.StatusBadRequest, nil, err)
			return
		}

		if value, err := stringutil.ConvertToInteger(params.ByName(`y`)); err == nil {
			y = int(value)
		} else {
			util.Respond(w, http.StatusBadRequest, nil, err)
			return
		}

		if err := self.MoveWindow(id, x, y); err == nil {
			util.Respond(w, http.StatusAccepted, nil, nil)
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.PUT(`/api/session/windows/:id/resize/:x/:y`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		id := params.ByName(`id`)
		var width, height uint

		if value, err := stringutil.ConvertToInteger(params.ByName(`width`)); err == nil {
			width = uint(value)
		} else {
			util.Respond(w, http.StatusBadRequest, nil, err)
			return
		}

		if value, err := stringutil.ConvertToInteger(params.ByName(`height`)); err == nil {
			height = uint(value)
		} else {
			util.Respond(w, http.StatusBadRequest, nil, err)
			return
		}

		if err := self.ResizeWindow(id, width, height); err == nil {
			util.Respond(w, http.StatusAccepted, nil, nil)
		} else {
			util.Respond(w, http.StatusInternalServerError, nil, err)
		}
	})

	router.GET(`/api/session/applications`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		keys := make([]string, 0)

		for key, _ := range self.Applications.Entries {
			keys = append(keys, key)
		}

		sort.Strings(keys)

		util.Respond(w, http.StatusOK, keys, nil)
	})

	router.GET(`/api/session/applications/:name`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		key := params.ByName(`name`)

		if app, ok := self.Applications.Entries[key]; ok {
			util.Respond(w, http.StatusOK, app, nil)
		} else {
			util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Could not locate application '%s'", key))
		}
	})

	router.GET(`/api/session/icons/list/:type`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		var filterMinSize, filterMaxSize int

		rv := make([]string, 0)
		listType := params.ByName(`type`)

		//  filters
		filterThemes := strings.Split(req.URL.Query().Get(`themes`), `,`)
		filterIconContextTypes := strings.Split(req.URL.Query().Get(`contexts`), `,`)
		filterIconFileTypes := strings.Split(req.URL.Query().Get(`filetypes`), `,`)
		filterMinSizeS := req.URL.Query().Get(`minsize`)
		filterMaxSizeS := req.URL.Query().Get(`maxsize`)
		filterIsScalable := req.URL.Query().Get(`scalable`)

		if filterMinSizeS != `` {
			if v, err := stringutil.ConvertToInteger(filterMinSizeS); err == nil {
				filterMinSize = int(v)
			} else {
				util.Respond(w, http.StatusBadRequest, nil, err)
				return
			}
		}

		if filterMaxSizeS != `` {
			if v, err := stringutil.ConvertToInteger(filterMaxSizeS); err == nil {
				filterMaxSize = int(v)
			} else {
				util.Respond(w, http.StatusBadRequest, nil, err)
				return
			}
		}

		for _, theme := range self.Themeset.Themes {
			if len(filterThemes) > 0 && filterThemes[0] != `` {
				if !sliceutil.ContainsString(filterThemes, strings.ToLower(theme.InternalName)) {
					inInherited := false

					for _, inheritedThemeName := range theme.Inherits {
						if sliceutil.ContainsString(filterThemes, strings.ToLower(inheritedThemeName)) {
							inInherited = true
							break
						}
					}

					if !inInherited {
						continue
					}
				}
			}

			switch listType {
			case `themes`:
				if !sliceutil.ContainsString(rv, theme.Name) {
					rv = append(rv, theme.InternalName)
				}
			default:
				for _, icon := range theme.Icons {
					//  filter context types
					if len(filterIconContextTypes) > 0 && filterIconContextTypes[0] != `` {
						if !sliceutil.ContainsString(filterIconContextTypes, strings.ToLower(icon.Context.Name)) {
							continue
						}
					}

					//  filter icon filetypes
					if len(filterIconFileTypes) > 0 && filterIconFileTypes[0] != `` {
						if !sliceutil.ContainsString(filterIconFileTypes, icon.Type) {
							continue
						}
					}

					//  filter icon size contraints
					if filterMinSize > 0 && icon.Context.MinSize < filterMinSize {
						continue
					}

					if filterMaxSize > 0 && icon.Context.MaxSize > filterMaxSize {
						continue
					}

					//  filter for scalable/non-scalable icons
					if filterIsScalable == `true` && icon.Context.Type != icons.IconContextScalable {
						continue
					} else if filterIsScalable == `false` && icon.Context.Type == icons.IconContextScalable {
						continue
					}

					var value string

					switch listType {
					case `names`:
						value = icon.Name
					case `contexts`:
						value = strings.ToLower(icon.Context.Name)
					case `display-names`:
						value = icon.DisplayName
					case `sizes`:
						if v, err := stringutil.ToString(icon.Context.Size); err == nil {
							value = v
						}
					default:
						util.Respond(w, http.StatusBadRequest, nil, fmt.Errorf("Unrecognized list type '%s'", listType))
						return
					}

					if value != `` {
						if !sliceutil.ContainsString(rv, value) {
							rv = append(rv, value)
						}
					}
				}
			}
		}

		sort.Strings(rv)

		util.Respond(w, http.StatusOK, rv, nil)
	})

	router.GET(`/api/session/icons/view/:name/size/:size`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		var iconSize int

		iconNames := strings.Split(params.ByName(`name`), `,`)
		iconSizeS := params.ByName(`size`)
		themeName := req.URL.Query().Get(`theme`)

		if themeName == `` {
			themeName = self.Themeset.DefaultTheme
		}

		if v, err := stringutil.ConvertToInteger(iconSizeS); err == nil {
			iconSize = int(v)

			var icon *icons.Icon

			switch req.URL.Query().Get(`mode`) {
			case `hicolor-first`:
				if hiColorIcon, ok := self.Themeset.FindIconViaTheme(`hicolor`, iconNames, iconSize); ok {
					icon = hiColorIcon
				} else if themeIcon, ok := self.Themeset.FindIconViaTheme(themeName, iconNames, iconSize); ok {
					icon = themeIcon
				}
			default:
				if themeIcon, ok := self.Themeset.FindIconViaTheme(themeName, iconNames, iconSize); ok {
					icon = themeIcon
				}
			}

			if icon != nil {
				var contentType string

				switch icon.Type {
				case `png`:
					contentType = `image/png`
				case `svg`:
					contentType = `image/svg+xml`
				default:
					util.Respond(w, http.StatusBadRequest, nil, fmt.Errorf("Unsupported icon type '%s'", icon.Type))
					return
				}

				defer icon.Close()

				if data, err := ioutil.ReadAll(icon); err == nil {
					w.Header().Set(`Content-Type`, contentType)
					w.Write(data)
				} else {
					util.Respond(w, http.StatusBadRequest, nil, err)
				}
			} else {
				util.Respond(w, http.StatusNotFound, nil, fmt.Errorf("Could not locate icon"))
			}
		} else {
			util.Respond(w, http.StatusBadRequest, nil, err)
		}
	})

	// router.GET(`/api/session/applications/find/:pattern`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
	// })

	router.PUT(`/api/session/applications/:name/launch`, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		if err := self.Applications.LaunchEntry(params.ByName(`name`)); err == nil {
			util.Respond(w, http.StatusAccepted, nil, nil)
		} else {
			util.Respond(w, http.StatusNotFound, nil, err)
		}

	})

	return nil
}