//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) } username, err := util.GetByJSONPointer(authRequest, "/auth/passwordCredentials/username") if err != nil { http.Error(w, "", http.StatusBadRequest) } token, ok := fakeTokens[fmt.Sprintf("%v_token", username)] 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) }) 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) }) } }
func (routeUserDelete *RouteUserDelete) Routes(m *martini.ClassicMartini) { m.Post("/user/delete", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /user/delete") SetResponseJsonHeader(w) setupInfo := model.SetupInfo{} setupHandle := model.NewSetupHandle() if !setupHandle.GetSetupInfo(&setupInfo) { return model.GetErrorDtoJson("读取用户信息失败") } r.ParseForm() log.WriteLog("user delete %v", r.Form) userName := r.Form.Get("username") if common.USER_NAME_ADMIN == userName { log.WriteLog("删除admin失败") return model.GetErrorDtoJson("删除管理员信息失败") } if !setupInfo.DeleteUserByUserName(userName) { log.WriteLog("删除用户信息失败") return model.GetErrorDtoJson("删除用户信息失败") } if !setupHandle.SaveSetupInfo(&setupInfo) { log.WriteLog("保存删除用户信息失败") return model.GetErrorDtoJson("保存删除用户信息失败") } return model.GetDataDtoJson(nil) }) }
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) }) }
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" } } }) }
func testResponses(t *testing.T, m *martini.ClassicMartini, expectations ...*Expectation) { for _, expectation := range expectations { req, err := http.NewRequest("GET", "/test", strings.NewReader("")) reflect.ValueOf(req).Elem().FieldByName("RemoteAddr").SetString("1.2.3.4:5000") if err != nil { t.Error(err) } time.Sleep(expectation.Wait) recorder := httptest.NewRecorder() m.ServeHTTP(recorder, req) expectStatusCode(t, expectation.StatusCode, recorder.Code) if expectation.Body != "" { expectSame(t, recorder.Body.String(), expectation.Body) } expectSame(t, recorder.Header()["X-Ratelimit-Limit"][0], expectation.RateLimitLimit) expectSame(t, recorder.Header()["X-Ratelimit-Remaining"][0], expectation.RateLimitRemaining) resetTime, err := strconv.ParseInt(recorder.Header()["X-Ratelimit-Reset"][0], 10, 64) if err != nil { t.Errorf(err.Error()) } expectApproximateTimestamp(t, resetTime, expectation.RateLimitReset) } }
func (srv *httpServer) setupMiddleware(m *martini.ClassicMartini) { m.Use(render.Renderer(render.Options{ Directory: "templates", Layout: "layout", })) m.Use(CORSAllowAny()) }
func mapRoutes(m *martini.ClassicMartini) { m.Post("/githook", handleGitHook) m.Get("/auth", authGitHub) m.Get("/githubAuth", gitHubAuthMiddleware, getUserFromToken) m.Get("/award", gandalf, awardUser) m.Post("/submission", gandalf, csrf.Validate, handleSubmission) }
//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) }) } // }}}
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) }
//InitSession - initializes authentication middleware for controllers func InitSession(m *martini.ClassicMartini, rc redisCreds) { m.Use(render.Renderer()) if rediStore, err := sessions.NewRediStore(10, "tcp", rc.Uri(), rc.Pass(), []byte(sessionSecret)); err == nil { m.Use(sessions.Sessions(sessionName, rediStore)) } }
func RouterSiginInit(m *martini.ClassicMartini) { m.Group("/sign", func(r martini.Router) { r.Get("/in", SignIn) r.Post("/in/todo", SignInTodo) r.Get("/up", SignUp) r.Post("/up/todo", SignUpTodo) }) }
// 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) }
func InitDebugMiddleware(m *martini.ClassicMartini) { m.Use(PARAMS) m.Use(DB()) m.Use(sessions.Sessions("lol_session", sessions.NewCookieStore([]byte("secret123")))) m.Use(render.Renderer(render.Options{Directory: TemplatesLocation})) m.Use(martini.Static("resources/public", martini.StaticOptions{Prefix: "/public"})) SetId("1", "10153410152015744", "Sean Myers") // Me. Set these to act like facebook, using a nice cache }
func RouterUserInit(m *martini.ClassicMartini) { m.Group("/user", func(r martini.Router) { r.Get("/list", ListUser) r.Get("/upd/:id", UpdUser) r.Post("/upd/todo", UpdUserTodo) r.Get("/del/:id", DelUser) }, middlewares.Auth()) }
// martini router func route(m *martini.ClassicMartini) { // regist a device m.Post("/v1/devices/registration", binding.Json(DeviceRegisterArgs{}), RegisterDevice) // auth device // m.Post("v1/devices/authentication", binding.Json(DeviceAuthArgs{}), actions.AuthDevice) }
func Initialize(m *martini.ClassicMartini) { fmt.Println("Running in production environment") newRelicLicenseKey := os.Getenv("NEW_RELIC_LICENSE_KEY") if len(newRelicLicenseKey) > 0 { gorelic.InitNewrelicAgent(newRelicLicenseKey, AppName, true) m.Use(gorelic.Handler) } }
func InitLogger(m *martini.ClassicMartini) *os.File { f, err := os.OpenFile("logfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(err) } m.Map(log.New(f, "[martini]", log.LstdFlags)) return f }
func SetupRoutes(db *mgo.Database, m *martini.ClassicMartini) { m.Group("/oauth", func(r martini.Router) { r.Get("/register/:type", modules.Register) r.Get("/github", binding.Bind(models.GithubOAuth{}), modules.GithubOAuth) }) m.Group("/api/user", func(r martini.Router) { r.Put("/", binding.Bind(models.User{}), api.RegisterUser) }) }
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)) } }) }
func RoutePage(m *martini.ClassicMartini) { m.Group("/appmanager", func(r martini.Router) { r.Get("", page_index) r.Get("/channel/list", page_channel_list) r.Get("/version/add", page_version_add) r.Get("/channel/add", page_channel_add) r.Post("/version/add", version_add) r.Post("/channel/add/submit", binding.Bind(ChannelAddForm{}), channel_add) }) }
func initMySQL(m *martini.ClassicMartini) *sqlx.DB { db, err := sqlx.Connect("mysql", "test:test@tcp(127.0.0.1:3306)/instagram") if err != nil { log.Fatalln(err) } m.Map(db) return db }
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) }) }
func InitRoutes(m *martini.ClassicMartini) { m.Get("/", ListBlogs) m.Get("/new", NewBlog) m.Post("/new", binding.Form(models.Post{}), CreateBlog) m.Get("/post/:id", ShowBlog) m.NotFound(func(r render.Render) { fmt.Println("....................................................") r.HTML(404, "status/404", "") }) }
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) }) }
// Configure creates a default newrelic client and adds middleware and such func Configure(m *martini.ClassicMartini) error { cfg, err := config.LoadEnv() if err != nil { return err } ctl := control.NewAgentController(cfg) m.MapTo(ctl, (*control.Controller)(nil)) m.Use(NewRelicMiddleware(cfg)) return nil }
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) }) }) }
func (routeServerConfigSave *routeServerConfigSave) Routes(m *martini.ClassicMartini) { m.Post("/server/saveconfig", func(w http.ResponseWriter, r *http.Request, re render.Render) string { log.WriteLog("addr: /server/saveconfig") shttp.SetResponseJsonHeader(w) r.ParseForm() err := service.NewServerConfigSaveRequestHandle().Save(r) if nil != err { return model.GetErrorObjDtoJson(err) } return model.GetDataDtoJson("") }) }
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}) }) }
func configRender(m *martini.ClassicMartini) { m.Use(render.Renderer(render.Options{ Directory: "templates", // Specify what path to load the templates from. Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template. Extensions: []string{".tmpl.html", ".html", ".tmpl"}, // Specify extensions to load for templates. //Funcs: []template.FuncMap{AppHelpers}, // Specify helper function maps for templates to access. //Delims: render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings. //Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8". //IndentJSON: true, // Output human readable JSON //IndentXML: true, // Output human readable XML //HTMLContentType: "application/xhtml+xml", // Output XHTML content type instead of default "text/html" })) }
func (routeUserSave *RouteUserSave) Routes(m *martini.ClassicMartini) { m.Post("/user/save", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /user/save") SetResponseJsonHeader(w) setupInfo := model.SetupInfo{} setupHandle := model.NewSetupHandle() if !setupHandle.GetSetupInfo(&setupInfo) { return model.GetErrorDtoJson("读取用户信息失败") } r.ParseForm() log.WriteLog("user save %v", r.Form) ousername := r.Form.Get("ousername") username := r.Form.Get("username") addFlag := utils.IsEmptyStr(ousername) password := r.Form.Get("password") if utils.IsEmptyStr(username) { return model.GetErrorDtoJson("没有用户名称") } if utils.IsEmptyStr(password) { return model.GetErrorDtoJson("没有密码") } index := setupInfo.GetUserIndexByUserName(username) oindex := setupInfo.GetUserIndexByUserName(ousername) var pUserInfo *model.UserInfo = nil if addFlag { if index > -1 { return model.GetErrorDtoJson("用户名称输入重复") } userInfo := model.UserInfo{UserName: username, Password: password} setupInfo.AddUserInfo(userInfo) pUserInfo = &userInfo } else { if oindex < 0 { return model.GetErrorDtoJson("没有找到用户") } else { if index > -1 && oindex != index { return model.GetErrorDtoJson("用户名称输入重复") } } setupInfo.Users[oindex].UserName = username setupInfo.Users[oindex].Password = password pUserInfo = &setupInfo.Users[oindex] } if !setupHandle.SaveSetupInfo(&setupInfo) { log.WriteLog("保存删除用户信息失败") return model.GetErrorDtoJson("保存删除用信息失败") } return model.GetDataDtoJson(model.UserSaveInfo{UserInfo: *pUserInfo, OUserName: ousername, AddFlag: addFlag}) }) }