Exemplo n.º 1
0
func AddWs(m *martini.ClassicMartini, c *container.ContainerBag) {
	clientList = newClientList()

	go monitorBuilders(c)

	m.Get("/ws", sockets.JSON(Message{}),
		func(params martini.Params,
			receiver <-chan *Message,
			sender chan<- *Message,
			done <-chan bool,
			disconnect chan<- int,
			err <-chan error) (int, string) {

			client := &Client{receiver, sender, done, err, disconnect}
			clientList.appendClient(client)

			for {
				select {
				case <-client.done:
					clientList.removeClient(client)
					return 200, "OK"
				}
			}
		})
}
Exemplo n.º 2
0
//controller转发规则设置
func controller(m *martini.ClassicMartini) { // {{{
	m.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	m.Group("/schedules", func(r martini.Router) {
		//Schedule部分
		r.Get("", GetSchedules)
		r.Post("", binding.Bind(schedule.Schedule{}), AddSchedule)
		r.Get("/:id", GetScheduleById)
		r.Put("/:id", binding.Bind(schedule.Schedule{}), UpdateSchedule)
		r.Delete("/:id", DeleteSchedule)

		//Job部分
		r.Get("/:sid/jobs", GetJobsForSchedule)
		r.Post("/:sid/jobs", binding.Bind(schedule.Job{}), AddJob)
		r.Put("/:sid/jobs/:id", binding.Bind(schedule.Job{}), UpdateJob)
		r.Delete("/:sid/jobs/:id", DeleteJob)

		//Task部分
		r.Post("/:sid/jobs/:jid/tasks", binding.Bind(schedule.Task{}), AddTask)
		r.Put("/:sid/jobs/:jid/tasks/:id", binding.Bind(schedule.Task{}), UpdateTask)
		r.Delete("/:sid/jobs/:jid/tasks/:id", DeleteTask)

		//TaskRelation部分
		r.Post("/:sid/jobs/:jid/tasks/:id/reltask/:relid", AddRelTask)
		r.Delete("/:sid/jobs/:jid/tasks/:id/reltask/:relid", DeleteRelTask)
	})

} // }}}
Exemplo n.º 3
0
func (routeServerGeneralInfo *RouteServerGeneralInfo) Routes(m *martini.ClassicMartini) {
	m.Get("/server/info/general", func(w http.ResponseWriter, r *http.Request) string {
		log.WriteLog("addr: /server/info/general")
		shttp.SetResponseJsonHeader(w)
		result := map[string]string{}
		val, err := service.NewGetSystemTimeInfo().GetInfo()
		if nil != err {
			return model.GetErrorObjDtoJson(err)
		}
		result["time"] = val
		runTimeInfo, err1 := service.NewGetSystemRunTimeInfo().GetInfo()
		if nil != err1 {
			return model.GetErrorObjDtoJson(err1)
		}
		result["runtime"] = fmt.Sprintf("%d天 %d小时 %d分钟", runTimeInfo.Day, runTimeInfo.Hour, runTimeInfo.Min)
		hostname, err3 := os.Hostname()
		if nil != err3 {
			return model.GetErrorObjDtoJson(err3)
		}
		result["hostname"] = hostname
		ver, err2 := utils.CmdOutputNoLn("uname", "-r")
		if nil != err2 {
			return model.GetErrorObjDtoJson(err2)
		}
		result["kernel"] = ver
		return model.GetDataDtoJson(result)
	})
}
Exemplo n.º 4
0
// RegisterRequests makes for the de-facto list of known API calls
func (this *HttpAgentsAPI) RegisterRequests(m *martini.ClassicMartini) {
	m.Get("/api/submit-agent/:host/:port/:token", this.SubmitAgent)
	m.Get("/api/host-attribute/:host/:attrVame/:attrValue", this.SetHostAttribute)
	m.Get("/api/host-attribute/attr/:attr/", this.GetHostAttributeByAttributeName)
	m.Get("/api/agents-hosts", this.AgentsHosts)
	m.Get("/api/agents-instances", this.AgentsInstances)
	m.Get("/api/agent-ping", this.AgentPing)
}
Exemplo n.º 5
0
func (routeRoot *RouteRoot) Routes(m *martini.ClassicMartini) {
	m.Get("/", func(w http.ResponseWriter, r *http.Request, re render.Render) {
		log.WriteLog("addr: /")
		if !CheckSessionUserLogin(w, r) {
			gotoLoginPage(w, r, re)
		} else {
			gotoRootPage(re, GetSessionUserInfo(w, r))
		}
	})
}
Exemplo n.º 6
0
func (routeServerNetCardInfo *RouteServerNetCardInfo) Routes(m *martini.ClassicMartini) {
	m.Get("/server/info/netcard", func(w http.ResponseWriter, r *http.Request) string {
		log.WriteLog("addr: /server/info/netcard")
		shttp.SetResponseJsonHeader(w)
		result, err := service.NewGetNetStatisticsInfo().GetInfo()
		if nil != err {
			return model.GetErrorObjDtoJson(err)
		}
		return model.GetDataDtoJson(result)
	})
}
Exemplo n.º 7
0
func initFunnyRouter(m *martini.ClassicMartini) {
	stats := initStats()
	m.Get("/player/stats", func(renderer render.Render) {
		renderer.JSON(200, stats)
	})

	m.Get("/stats", func(renderer render.Render) {
		renderer.HTML(200, "stats", stats)
	})

}
Exemplo n.º 8
0
func RegisterWebService(server *martini.ClassicMartini) {
	path := "/api/v1/keys"

	server.Get(path, Get)
	//server.Get(path+"/:email", Get)

	server.Post(path, Post)

	server.Delete(path, Delete)
	server.Delete(path+"/:id", Delete)
}
Exemplo n.º 9
0
func RegisterRESTFunction(f RESTFunction, cm *martini.ClassicMartini) {
	path := f.GetPath()

	cm.Get(path, f.RGet)
	cm.Get(path+"/:id", f.RGet)

	cm.Post(path, f.RPost)
	cm.Post(path+"/:id", f.RPost)

	cm.Delete(path, f.RDelete)
	cm.Delete(path+"/:id", f.RDelete)
}
Exemplo n.º 10
0
func mapRoutes(server *martini.ClassicMartini) {

	server.Get("/", controller.Home)

	server.Group("/api", func(apiRoutes martini.Router) {
		apiRoutes.Get("/pages", api.PageIndex)
		apiRoutes.Get("/pages/:id", api.PageShow)
		apiRoutes.Group("/pages/:pageId", func(pageRoutes martini.Router) {
			pageRoutes.Get("/posts", api.PostIndex)
		})
	})
}
Exemplo n.º 11
0
func registerRoutes(server *martini.ClassicMartini) {
	// Box
	server.Post("/boxes", binding.Bind(request.CreateRequest{}), boxCreate)
	server.Put("/boxes/:name", binding.Bind(request.DeployRequest{}), boxDeploy)
	server.Get("/boxes", boxList)
	server.Get("/boxes/:name", boxInspect)
	server.Delete("/boxes/:name", boxDelete)

	// Domain
	server.Post("/boxes/:name/domain", binding.Bind(request.Domain{}), domainAdd)
	server.Delete("/boxes/:name/domain/:domain", domainDelete)
}
Exemplo n.º 12
0
// RegisterWebService adds martini routes to the relevant webservice methods
// based on the path returned by GetPath. Each method is registered once for
// the collection and once for each id in the collection.
func RegisterWebService(webService WebService,
	classicMartini *martini.ClassicMartini) {
	path := webService.GetPath()

	classicMartini.Get(path, webService.WebGet)
	classicMartini.Get(path+"/:id", webService.WebGet)

	classicMartini.Post(path, webService.WebPost)
	classicMartini.Post(path+"/:id", webService.WebPost)

	classicMartini.Delete(path, webService.WebDelete)
	classicMartini.Delete(path+"/:id", webService.WebDelete)
}
Exemplo n.º 13
0
func (routeServerMemInfo *RouteServerMemInfo) Routes(m *martini.ClassicMartini) {
	m.Get("/server/info/mem", func(w http.ResponseWriter, r *http.Request) string {
		log.WriteLog("addr: /server/info/mem")
		shttp.SetResponseJsonHeader(w)
		mem, err := service.NewGetMemInfo().GetInfo()
		if nil != err {
			return model.GetErrorObjDtoJson(err)
		}
		memFree := mem.MemFree + mem.Buffers + mem.Cached
		memUsed := mem.MemTotal - memFree
		return model.GetDataDtoJson([]interface{}{mem.MemTotal, memUsed, memFree})
	})
}
Exemplo n.º 14
0
func routes(m *martini.ClassicMartini) {

	m.Get("/", func() string {
		return "Hello World!"
	})

	m.Get("/store/:key/:value", func(p martini.Params, db Database) string {
		key := p["key"]
		value := p["value"]
		db[key] = value

		return "Stored " + value + " in " + key
	})

	m.Get("/get/:key", func(p martini.Params, db Database) string {
		key := p["key"]
		value := db[key]
		return value
	})

	m.Get("/hello/:name", func(p martini.Params) string {
		return "Hello " + p["name"]
	})

}
Exemplo n.º 15
0
//InitRoutes - initialize the mappings for controllers against valid routes
func InitRoutes(m *martini.ClassicMartini, redisConn Doer, mongoConn pezdispenser.MongoCollectionGetter, authClient AuthRequestCreator) {
	setOauthConfig()
	keyGen := NewKeyGen(redisConn, &GUIDMake{})
	m.Use(render.Renderer())
	m.Use(martini.Static(StaticPath))
	m.Use(oauth2.Google(OauthConfig))
	authKey := NewAuthKeyV1(keyGen)

	m.Get("/info", authKey.Get())
	m.Get(ValidKeyCheck, NewValidateV1(keyGen).Get())

	m.Get("/me", oauth2.LoginRequired, DomainCheck, NewMeController().Get())

	m.Get("/", oauth2.LoginRequired, DomainCheck, func(params martini.Params, log *log.Logger, r render.Render, tokens oauth2.Tokens) {
		userInfo := GetUserInfo(tokens)
		r.HTML(SuccessStatus, "index", userInfo)
	})

	m.Post("/sandbox", oauth2.LoginRequired, DomainCheck, NewSandBoxController().Post())

	m.Group(URLAuthBaseV1, func(r martini.Router) {
		r.Put(APIKey, authKey.Put())
		r.Get(APIKey, authKey.Get())
		r.Delete(APIKey, authKey.Delete())
	}, oauth2.LoginRequired, DomainCheck)

	m.Group(URLOrgBaseV1, func(r martini.Router) {
		pcfOrg := NewOrgController(mongoConn, authClient)
		r.Put(OrgUser, pcfOrg.Put())
		r.Get(OrgUser, pcfOrg.Get())
	}, oauth2.LoginRequired, DomainCheck)
}
Exemplo n.º 16
0
func (routeServerList *RouteServerList) Routes(m *martini.ClassicMartini) {
	m.Get("/serverList", func(w http.ResponseWriter, r *http.Request, re render.Render) {
		log.WriteLog("addr: /serverList")

		serverName := getUniqueServerName()
		if utils.IsEmptyStr(serverName) {
			routeServerList.routeMoreServer(r, re)
		} else {
			gotoServerInfo(w, r, re)
		}

	})

}
Exemplo n.º 17
0
// martini router
func route(m *martini.ClassicMartini) {
	// find a device by key
	m.Get("/application/v1/device/info", GetDeviceInfoByKey)

	// find a device by identifier
	m.Get("/application/v1/devices/:identifier/info", ApplicationAuthOnDeviceIdentifer, GetDeviceInfoByIdentifier)

	// get devie current status
	m.Get("/application/v1/devices/:identifier/status/current",
		ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
		GetDeviceCurrentStatus)

	// get devie latest status
	m.Get("/application/v1/devices/:identifier/status/latest",
		ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
		GetDeviceLatestStatus)

	// set device status
	m.Put("/application/v1/devices/:identifier/status",
		ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
		SetDeviceStatus)

	// send a command to device
	m.Post("/application/v1/devices/:identifier/commands",
		ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
		SendCommandToDevice)

}
Exemplo n.º 18
0
func SetupRoutes(m *martini.ClassicMartini) {
	m.Get("/", Leaderboard)
	m.Get("/leaders", GetLeaders)
	m.Get("/leaders/:page", GetLeaders)
	m.Get("/leader/:name", GetLeader)
	m.Post("/leader", binding.Json(Leader{}), binding.ErrorHandler, PostLeader)
}
Exemplo n.º 19
0
func SetupAuth(martini *martini.ClassicMartini) {
	os.Mkdir(backendfile, 0755)
	backend_, err := httpauth.NewLeveldbAuthBackend(backendfile)
	if err != nil {
		log.Fatal(err.Error())
	}
	backend = backend_

	roles = make(map[string]httpauth.Role)
	roles["user"] = 30
	roles["admin"] = 80

	aaa, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles)
	if err != nil {
		log.Fatal(err.Error())
	}

	users, err := backend.Users()
	if err != nil || len(users) == 0 {
		// create a default user
		hash, err := bcrypt.GenerateFromPassword([]byte("toor"), bcrypt.DefaultCost)
		//hash, err := bcrypt.GenerateFromPassword([]byte("l4ngu4g3"), bcrypt.DefaultCost)
		if err != nil {
			panic(err)
		}
		defaultUser := httpauth.UserData{Username: "******", Email: "", Hash: hash, Role: "admin"}
		//defaultUser := httpauth.UserData{Username: "******", Email: "", Hash: hash, Role: "admin"}
		err = backend.SaveUser(defaultUser)
		if err != nil {
			panic(err)
		}
	}

	martini.Post("/auth/login", doLogin)
	martini.Get("/auth/logout", doLogout)
	martini.Get("/auth/token", doGetToken)

	martini.Post("/auth/user", AssertRole("admin"), doAddUser)

	martini.Get("/auth/currentuser", doGetCurrentUser)
	martini.Get("/auth/user", AssertRole("admin"), doGetUsers)
	martini.Get("/auth/user/:username", AssertRole("admin"), doGetUser)

	martini.Put("/auth/user/:username", AssertRole("admin"), doUpdateUser)
	martini.Delete("/auth/user/:username", AssertRole("admin"), doDeleteUser)
	martini.Post("/auth/user/:username/allow", AssertRole("admin"), doAllow)
	martini.Post("/auth/user/:username/forbid", AssertRole("admin"), doForbid)

}
Exemplo n.º 20
0
func Configure(m *martini.ClassicMartini) {
	m.Group("/humidity", func(r martini.Router) {
		r.Post("", humidity.Post)
		r.Get("", humidity.Get)
	})
	m.Get("/current/humidity", current_humidity.Get)

	m.Group("/", func(r martini.Router) {
		r.Get("", index.Get)
	})

	static := martini.Static("templates", martini.StaticOptions{Fallback: "/index.tmpl", Exclude: "/api/v"})
	m.NotFound(static, http.NotFound)
	m.Use(martini.Static("static"))
}
Exemplo n.º 21
0
func InitRoutes(m *martini.ClassicMartini) {

	m.Group("/devices", func(r martini.Router) {
		r.Get("", ListDevices)
		r.Post("", binding.Form(models.Device{}), CreateDevice)
		r.Get("/new", NewDevice)
		// r.Get("/:id", ShowDevice)
	})

	m.Get("/sock", Socket)
	m.Get("/node", Node)
	m.NotFound(func(r render.Render) {
		r.HTML(404, "status/404", "")
	})
}
Exemplo n.º 22
0
//FakeKeystone server for only test purpose
func FakeKeystone(martini *martini.ClassicMartini) {
	//mocking keystone v2.0 API
	martini.Post("/v2.0/tokens", func(w http.ResponseWriter, r *http.Request) {
		authRequest, err := ReadJSON(r)
		if err != nil {
			http.Error(w, "", http.StatusBadRequest)
		}
		var tokenKey string
		username, err := util.GetByJSONPointer(authRequest, "/auth/passwordCredentials/username")
		if err == nil {
			tokenKey = fmt.Sprintf("%v_token", username)
		} else {
			username, err = util.GetByJSONPointer(authRequest, "/auth/token/id")
			tokenKey = fmt.Sprintf("%v", username)
			if err != nil {
				http.Error(w, "", http.StatusBadRequest)
			}
		}

		token, ok := fakeTokens[tokenKey]
		if !ok {
			http.Error(w, "", http.StatusUnauthorized)
		}

		serializedToken, _ := json.Marshal(token)
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Content-Length", strconv.Itoa(len(serializedToken)))
		w.Write(serializedToken)
	})

	martini.Get("/v2.0/tenants", func(w http.ResponseWriter, r *http.Request) {
		tenants := map[string]interface{}{
			"tenants": allTenants,
		}

		serializedToken, _ := json.Marshal(tenants)
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Content-Length", strconv.Itoa(len(serializedToken)))
		w.Write(serializedToken)
	})

	for tokenID, rawToken := range fakeTokens {
		serializedToken, _ := json.Marshal(rawToken)
		martini.Get("/v2.0/tokens/"+tokenID, func(w http.ResponseWriter, r *http.Request) {
			w.Write(serializedToken)
		})
	}
}
Exemplo n.º 23
0
func (routeLogin *RouteLogin) Routes(m *martini.ClassicMartini) {

	m.Get("/login", func(w http.ResponseWriter, r *http.Request, re render.Render) {
		gotoLoginPage(w, r, re)
	})

	m.Post("/login", func(w http.ResponseWriter, r *http.Request, re render.Render) {
		r.ParseForm()
		userInfo := checkLoginUser(r.Form, re, "login")
		if nil != userInfo {
			userInfo.SetLoginState()
			shttp.SetSessionUserInfo(w, r, userInfo)
			gotoRootPage(re, userInfo)
		}
	})
}
Exemplo n.º 24
0
func (routeServerConfigRoot *routeServerConfigRoot) Routes(m *martini.ClassicMartini) {
	m.Get("/serverconfig", func(w http.ResponseWriter, r *http.Request, re render.Render) string {
		log.WriteLog("addr: /serverconfig")
		shttp.SetResponseJsonHeader(w)
		r.ParseForm()
		serverName := r.FormValue("servername")
		if utils.IsEmptyStr(serverName) {
			return model.GetErrorDtoJson("没有服务器名称")
		}
		serverInfo, serverSetupInfo, err := service.NewGetServerSetupInfo().GetInfo(serverName)
		if nil != err {
			return model.GetErrorObjDtoJson(err)
		}
		return model.GetDataDtoJson([]interface{}{serverInfo, serverSetupInfo})
	})
}
Exemplo n.º 25
0
func Router(m *martini.ClassicMartini) {
	m.Get("/", controller.Index)
	m.Get("/upload_records", controller.UploadRecords)
	m.Post("/upload_records", controller.UploadRecords)
	m.Get("/choose/exam", controller.ChooseExam)
	//答题
	m.Get("/answer", controller.Answer)
	m.Post("/answer", controller.Answer)
}
Exemplo n.º 26
0
func (routeServerList *RouteServerList) Routes(m *martini.ClassicMartini) {

	m.Get("/serverList", func(w http.ResponseWriter, r *http.Request, re render.Render) {
		log.WriteLog("addr: /serverList")
		r.ParseForm()
		startPage, err := strconv.Atoi(r.FormValue("pageNo"))
		if nil != err {
			startPage = 0
		}
		serverPageInfo := model.NewServerPageHandle().GetServerPageInfo(startPage, 10)
		for index, _ := range serverPageInfo.Servers {
			serverPageInfo.Servers[index].Status = utils.GetServerState(serverPageInfo.Servers[index].Address)
		}
		re.HTML(200, "serverList", serverPageInfo)
	})

}
Exemplo n.º 27
0
Arquivo: user.go Projeto: xrstf/raziel
func setupUsersCtrl(app *martini.ClassicMartini) {
	app.Group("/users", func(r martini.Router) {
		app.Get("", usersIndexAction)
		app.Get("/add", usersAddAction)
		app.Post("", sessions.RequireCsrfToken, usersCreateAction)
		app.Get("/:id", usersEditAction)
		app.Put("/:id", sessions.RequireCsrfToken, usersUpdateAction)
		app.Delete("/:id", sessions.RequireCsrfToken, usersDeleteAction)
		app.Get("/:id/delete", usersDeleteConfirmAction)
	}, sessions.RequireLogin)
}
Exemplo n.º 28
0
Arquivo: main.go Projeto: kyf/compass
func showTemplate(pathes []string, m *martini.ClassicMartini) {
	for _, p := range pathes {
		m.Get(fmt.Sprintf("/%s", p), (func(p string) func(http.ResponseWriter, *http.Request, sessions.Session, *log.Logger) {
			return func(w http.ResponseWriter, r *http.Request, s sessions.Session, logger *log.Logger) {
				w.Header().Set("content-type", "text/html")
				if ok := isLogin(w, r, s); !ok {
					w.Write([]byte(SCRIPT_LOGIN))
					return
				}
				var t *template.Template
				t, err := template.ParseFiles(fmt.Sprintf("../../admin/static/html/%s.html", p))
				if err != nil {
					log.Fatal(err)
				}
				t.Execute(w, nil)
			}
		})(p))
	}
}
Exemplo n.º 29
0
func route(m *martini.ClassicMartini) {
	users := &controller.UsersController{}

	m.Get("/", func() string {
		return "Hello world!"
	})
	// m.Get("/users/:user_id", func(params martini.Params) string {
	// 	return "GET users user_id=" + params["user_id"]
	// })
	// m.Post("/users/:user_id", func(params martini.Params) string {
	// 	return "Post users user_id=" + params["user_id"]
	// })
	// m.Put("/users/:user_id", func(params martini.Params) string {
	// 	return "Put users user_id=" + params["user_id"]
	// })
	// m.Delete("/users/:user_id", func(params martini.Params) string {
	// 	return "Delete users user_id=" + params["user_id"]
	// })
	m.Get("/comm/userinfo/userinfoserv/getinfo*", users.GetInfo)
}
Exemplo n.º 30
0
func Module(m *martini.ClassicMartini, apiPath string) {
	addInhabitantRoutes(m)
	addPlantRoutes(m)
	addCoralRoutes(m)
	addInvertebrateRoutes(m)
	addComponentRoutes(m)
	addLatestNewsRoutes(m)

	m.Get("/api", GetAllInJson)
	m.Get("/"+apiPath, GetAllInJson)
	m.Get("/media/del/:id", DeleteMedia)
	m.Get("/family_names", ShowFamilyNames)
}