Exemple #1
0
func main() {
	app := martini.Classic()

	app.Use(db.DB())
	app.Use(martini.Static("public"))
	app.Use(render.Renderer(render.Options{
		Directory:  "views",
		Layout:     "layout",
		Extensions: []string{".html"},
	}))

	app.Get("/", handlers.IndexHandler)

	app.Group("/api", func(route martini.Router) {

		route.Get("/info", handlers.GetInfoHandler)

		route.Get("/items", handlers.GetItemsHandler)
		route.Get("/items/:id", handlers.GetItemHandler)
		route.Post("/items", binding.Json(types.Item{}), handlers.PostItemHandler)
		route.Delete("/items/:id", handlers.DeleteItemHandler)
		route.Put("/items/:id", binding.Json(types.Item{}), handlers.UpdateItemHandler)
	})

	http.ListenAndServe(config.Get("dev").Port, app)
}
Exemple #2
0
func apiv1() {
	url := "/api/v1"
	m.Group(url+"/workplace", func(router martini.Router) {
		router.Post("/auth", binding.Json(controllers.InputWorkplaceAuth{}), controllers.WorkplaceAuth)
		//router.Post("/test", binding.Json(controllers.Test{}), controllers.WorkplacePing)
		//router.Post("/add", binding.Json(controllers.Add{}), controllers.WorkplaceAdd)
		//update
		//delete
		//import

	}, render.Renderer())

	m.Group(url+"/promocode", func(router martini.Router) {

		router.Post("/calc", binding.Json(controllers.InputPromocodeCalc{}), controllers.PromocodeCalc)
		//update
		//delete
		//import

	}, render.Renderer())

	m.Group(url+"/document", func(router martini.Router) {

		router.Post("/add", binding.Json(controllers.InputDocumentAdd{}), controllers.DocumentAdd)
		//update
		//delete
		//import

	}, render.Renderer())

}
Exemple #3
0
func (m *myClassic) UseApi(option ApiOption) error {

	aipOption = option

	m.Get("/api/v1/collections/:collectionId", getCollectionHandler)
	m.Put("/api/v1/collections/:collectionId", updateCollectionHandler)
	m.Delete("/api/v1/collections/:collectionId", deleteCollectionHandler)
	m.Get("/api/v1/collections", getCollectionsHandler)
	m.Post("/api/v1/collections", binding.Json(Collection{}), binding.ErrorHandler, createCollectionHandler)

	m.Get("/api/v1/products/:productId", getProductHandler)
	m.Post("/api/v1/products", binding.Json(Product{}), binding.ErrorHandler, createProductHandler)

	m.Get("/api/v1/themes/:themeName", getThemeHandler)
	m.Get("/api/v1/themes", getThemesHandler)
	m.Post("/api/v1/themes", binding.Json(Theme{}), binding.ErrorHandler, createThemeHandler)

	m.Get("/api/v1/pages", getPageHandler)
	m.Post("/api/v1/pages", binding.Json(Page{}), binding.ErrorHandler, createPageHandler)

	m.Get("/api/v1/templates/:templateName", getTemplateHandler)
	m.Get("/api/v1/templates", getTemplatesHandler)
	m.Post("/api/v1/templates", binding.Json(Template{}), binding.ErrorHandler, createTemplateHandler)

	return nil
}
Exemple #4
0
// 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{}), AuthDevice)

}
Exemple #5
0
func createHttpHandler() http.Handler {
	m := martini.Classic()
	m.Use(render.Renderer())

	// Make sure server is still responsive
	m.Get("/ping", func() (int, string) {
		return http.StatusOK, "pong"
	})

	m.Get("/v1/citizens", func(params martini.Params, r render.Render) {
		citizens := cases.FindCitizens()
		response := make([]Citizen, len(citizens), len(citizens))
		for i, citizen := range citizens {
			response[i].from(citizen)
		}
		r.JSON(http.StatusOK, response)
	})
	m.Post("/v1/citizens", binding.Json(Citizen{}), func(citizen Citizen, r render.Render) {
		if citizen, err := cases.CreateCitizen(citizen.UID, citizen.Secret); err != nil {
			r.JSON(http.StatusBadRequest, err)
		} else {
			response := Citizen{}
			response.from(citizen)
			r.JSON(http.StatusOK, response)
		}
	})

	m.Patch("/v1/citizens/:uid", binding.Json(Citizen{}), func(params martini.Params, attributes Citizen, r render.Render) {
		if citizen, err := cases.UpdateCitizen(params["uid"], attributes.to()); err != nil {
			r.JSON(http.StatusBadRequest, err)
		} else {
			response := Citizen{}
			response.from(citizen)
			r.JSON(http.StatusOK, response)
		}
	})

	m.Get("/v1/citizens/:uid", func(params martini.Params, r render.Render) {
		if citizen, err := cases.FindCitizen(params["uid"]); err != nil {
			r.JSON(http.StatusBadRequest, err)
		} else {
			response := Citizen{}
			response.from(citizen)
			r.JSON(http.StatusOK, response)
		}
	})

	m.Put("/v1/identify", func(params martini.Params) (int, string) {
		if token, err := cases.LoginCitizen(params["uid"], params["secret"]); err != nil {
			return http.StatusInternalServerError, ""
		} else {
			return http.StatusOK, token
		}
	})

	return m
}
Exemple #6
0
func BindTaskApi(m *martini.ClassicMartini) {
	m.Get("/admin/task/list", binding.Form(tasklistForm{}), adminErrorHandler, tasklistHandler)
	m.Get("/admin/task/timeline", binding.Form(userTaskForm{}), adminErrorHandler, userTaskHandler)
	//m.Get("/admin/task/timeline", binding.Form(taskTimelineForm{}), adminErrorHandler, taskTimelineHandler)
	m.Post("/admin/task/auth", binding.Json(taskAuthForm{}), adminErrorHandler, taskAuthHandler)
	m.Options("/admin/task/auth", optionsHandler)
	m.Post("/admin/task/auth_list", binding.Json(taskAuthListForm{}), adminErrorHandler, taskAuthListHandler)
	m.Options("/admin/task/auth_list", optionsHandler)
}
func NewTestServer() *httptest.Server {
	m := createServer()

	// Errors
	m.Get("/throw400", throw400)
	m.Get("/throw401", throw401)
	m.Get("/throw404", throw404)

	// Charges
	m.Post("/charges", binding.Json(Charge{}), createCharge)
	m.Get("/charges/:chargeId", getCharge)
	m.Post("/charges/:chargeId/refund", refundCharge)

	// Customers
	m.Post("/customers", binding.Json(Customer{}), createCustomer)
	m.Put("/customers/:customerId", binding.Json(Customer{}), updateCustomer)
	m.Delete("/customers/:customerId", deleteCustomer)
	m.Post("/customers/:customerId/cards", binding.Json(CreditCard{}), createCard)
	m.Put("/customers/:customerId/cards/:cardId", binding.Json(CreditCard{}), updateCard)
	m.Delete("/customers/:customerId/cards/:cardId", deleteCard)
	m.Post("/customers/:customerId/subscription", binding.Json(Subscription{}), createSubscription)
	m.Put("/customers/:customerId/subscription", binding.Json(Subscription{}), updateSubscription)
	m.Post("/customers/:customerId/subscription/pause", pauseSubscription)
	m.Post("/customers/:customerId/subscription/resume", resumeSubscription)
	m.Post("/customers/:customerId/subscription/cancel", cancelSubscription)

	// Plans
	m.Post("/plans", binding.Json(Plan{}), createPlan)
	m.Put("/plans/:planId", binding.Json(Plan{}), updatePlan)
	m.Delete("/plans/:planId", deletePlan)

	return httptest.NewServer(m)
}
Exemple #8
0
func BindArticleApi(m *martini.ClassicMartini) {
	m.Get("/admin/article/info", binding.Form(articleInfoForm{}), adminErrorHandler, articleInfoHandler)
	m.Get("/admin/article/list", binding.Form(articleListForm{}), adminErrorHandler, articleListHandler)
	m.Get("/admin/article/timeline", binding.Form(articleListForm{}), adminErrorHandler, articleTimelineHandler)
	m.Get("/admin/article/comments", binding.Form(articleListForm{}), adminErrorHandler, articleCommentsHandler)
	m.Options("/admin/article/post", articlePostOptionsHandler)
	m.Post("/admin/article/post", binding.Json(postForm{}), adminErrorHandler, articlePostHandler)
	m.Post("/admin/article/delete", binding.Json(delArticleForm{}), adminErrorHandler, delArticleHandler)
	m.Get("/admin/article/search", binding.Form(articleSearchForm{}), adminErrorHandler, articleSearchHandler)
	m.Post("/admin/article/update", binding.Json(articleUpdateForm{}), adminErrorHandler, articleUpdateHandler)
}
Exemple #9
0
func BindArticleApi(m *martini.ClassicMartini) {
	m.Post("/1/article/new",
		binding.Json(newArticleForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		newArticleHandler)
	m.Post("/1/article/delete",
		binding.Json(deleteArticleForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		deleteArticleHandler)
	m.Post("/1/article/thumb",
		binding.Json(articleThumbForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		articleThumbHandler)
	m.Get("/1/article/is_thumbed",
		binding.Form(articleIsThumbedForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleIsThumbedHandler)
	m.Get("/1/article/timelines",
		binding.Form(articleListForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleListHandler)
	m.Get("/1/article/get",
		binding.Form(articleInfoForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleInfoHandler)
	m.Post("/1/article/comments",
		binding.Json(articleCommentsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleCommentsHandler)
	m.Get("/1/aritcle/thumbList",
		binding.Form(thumbersForm{}),
		thumbersHandler)
	m.Get("/1/article/news",
		binding.Form(articleNewsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleNewsHandler)
}
Exemple #10
0
func BindTaskApi(m *martini.ClassicMartini) {
	m.Get("/1/tasks/get",
		binding.Form(getTaskForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		getTaskHandler)
	m.Get("/1/tasks/getList",
		binding.Form(getTasksForm{}),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		getTasksHandler)
	m.Get("/1/tasks/getInfo",
		binding.Form(getTaskInfoForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		//loadUserHandler,
		getTaskInfoHandler)
	m.Get("/1/tasks/result",
		binding.Form(getTaskResultForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		//loadUserHandler,
		getTaskResultHandler)
	m.Post("/1/tasks/execute",
		binding.Json(completeTaskForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		completeTaskHandler)
	m.Get("/1/tasks/referrals",
		binding.Form(taskReferralForm{}),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		taskReferralsHandler)
	m.Post("/1/tasks/share",
		binding.Json(taskShareForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		taskShareHandler)
	m.Post("/1/tasks/shared",
		binding.Json(taskSharedForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		taskSharedHandler)
}
func main() {
	m := martini.Classic()

	m.Use(render.Renderer())

	m.Get("/tasks", ListTasks)
	m.Get("/tasks/:id", GetTask)
	m.Post("/tasks", binding.Json(Task{}), AddTask)
	m.Put("/tasks/:id", binding.Json(Task{}), UpdateTask)

	m.Map(initDb("dev.db"))

	m.Run()
}
Exemple #12
0
func BindUserApi(m *martini.ClassicMartini) {
	m.Post("/1/user/send_device_token",
		binding.Json(sendDevForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		sendDevHandler)
	m.Post("/1/user/set_push_enable",
		binding.Json(setPushForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		setPushHandler)
	m.Get("/1/user/is_push_enabled",
		binding.Form(pushStatusForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		pushStatusHandler)
	m.Post("/1/user/enableAttention",
		binding.Json(relationshipForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		followHandler)
	m.Post("/1/user/enableDefriend",
		binding.Json(relationshipForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		blacklistHandler)
	m.Get("/1/user/getAttentionFriendsList",
		binding.Form(getFollowsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getFollowsHandler)
	m.Get("/1/user/getAttentedMembersList",
		binding.Form(getFollowsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getFollowersHandler)
	m.Get("/1/user/getJoinedGroupsList",
		binding.Form(getFollowsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getGroupsHandler)
	m.Get("/1/user/getRelatedMembersList",
		binding.Form(socialListForm{}),
		ErrorHandler,
		socialListHandler)
}
Exemple #13
0
func main() {
	//lol if you don't already use swiftly
	username := os.Getenv("SWIFTLY_AUTH_USER")
	apikey := os.Getenv("SWIFTLY_AUTH_KEY")
	authurl := os.Getenv("SWIFTLY_AUTH_URL")
	region := os.Getenv("SWIFTLY_REGION")
	snet := os.Getenv("SWIFTLY_SNET")
	dockerized := os.Getenv("DOCKERIZED")
	memcacheOverride := os.Getenv("MEMCACHEADDR")
	if strings.ToLower(dockerized) == "true" {
		memcacheOverride = fmt.Sprintf("%s:%s", os.Getenv("MEMCACHED_PORT_11211_TCP_ADDR"), os.Getenv("MEMCACHED_PORT_11211_TCP_PORT"))
	}
	memcacheAddr := "127.0.0.1:11211"
	if memcacheOverride != "" {
		memcacheAddr = memcacheOverride
	}
	internal := false
	if strings.ToLower(snet) == "true" {
		internal = true
	}
	//martini looks for a HOST and PORT env var to determine what to listen on
	m := martini.Classic()

	cf := swift.Connection{
		UserName: username,
		ApiKey:   apikey,
		AuthUrl:  authurl,
		Region:   region,
		Internal: internal,
	}
	// Authenticate
	err := cf.Authenticate()
	PanicIf(err)
	m.Map(&cf)
	log.Println(os.Environ())
	log.Println(memcacheAddr)
	mc := memcache.New(memcacheAddr)
	m.Map(mc)

	m.Use(render.Renderer())

	m.Get("/", IndexPage)
	m.Get("/history", GetHistory)
	m.Get("/:pasteid", GetPaste)
	m.Get("/:pasteid/:format", GetPaste)
	m.Post("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Put("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Run()
}
Exemple #14
0
func StartServerMultiplesBotsHostPort(uri string, pathl string, host string, port string, newrelic *RelicConfig, bots ...*TgBot) {
	var puri *url.URL
	if uri != "" {
		tmpuri, err := url.Parse(uri)
		if err != nil {
			fmt.Printf("Bad URL %s", uri)
			return
		}
		puri = tmpuri
	}

	botsmap := make(map[string]*TgBot)
	for _, bot := range bots {
		tokendiv := strings.Split(bot.Token, ":")
		if len(tokendiv) != 2 {
			return
		}

		tokenpath := fmt.Sprintf("%s%s", tokendiv[0], tokendiv[1])
		botpathl := path.Join(pathl, tokenpath)

		nuri, _ := puri.Parse(botpathl)
		remoteuri := nuri.String()
		res, error := bot.SetWebhook(remoteuri)

		if error != nil {
			ec := res.ErrorCode
			fmt.Printf("Error setting the webhook: \nError code: %d\nDescription: %s\n", &ec, res.Description)
			continue
		}
		if bot.MainListener == nil {
			bot.StartMainListener()
		}
		botsmap[tokenpath] = bot
	}

	pathtolisten := path.Join(pathl, "(?P<token>[a-zA-Z0-9-_]+)")

	m := martini.Classic()
	m.Post(pathtolisten, binding.Json(MessageWithUpdateID{}), func(params martini.Params, msg MessageWithUpdateID) {
		bot, ok := botsmap[params["token"]]

		if ok && msg.UpdateID > 0 && msg.Msg.ID > 0 {
			bot.MainListener <- msg
		} else {
			fmt.Println("Someone tried with: ", params["token"], msg)
		}
	})

	if newrelic != nil {
		gorelic.InitNewrelicAgent(newrelic.Token, newrelic.Name, false)
		m.Use(gorelic.Handler)
	}

	if host == "" || port == "" {
		m.Run()
	} else {
		m.RunOnAddr(host + ":" + port)
	}
}
Exemple #15
0
func BindRecordApi(m *martini.ClassicMartini) {
	m.Post("/1/record/new",
		binding.Json(newRecordForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		newRecordHandler)
	m.Get("/1/record/get",
		binding.Form(getRecordForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getRecordHandler)
	m.Get("/1/record/timeline",
		binding.Form(recTimelineForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		recTimelineHandler)
	m.Get("/1/record/statistics",
		binding.Form(userRecStatForm{}),
		ErrorHandler,
		userRecStatHandler)
	m.Get("/1/leaderboard/list",
		binding.Form(leaderboardForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		leaderboardHandler)
	m.Get("/1/leaderboard/gameList",
		binding.Form(gamelbForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		gamelbHandler,
	)
}
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)
}
Exemple #17
0
func (srv *httpServer) setupRoutes(m *martini.ClassicMartini) {
	m.Get(`/`, func() string { return "every day" })
	m.Get(`/pusher/info`, srv.getPusherInfo)
	m.Post(`/apps/:app_id/events`, binding.Json(Event{}), srv.createAppEvents)
	m.Get(`/timeline/:id`, handleStatsJSONP)
	log.Printf("Set up HTTP Server routes on %#v\n", m)
}
Exemple #18
0
func BindWalletApi(m *martini.ClassicMartini) {
	m.Get("/1/wallet/get",
		binding.Form(walletForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		getWalletHandler)
	m.Get("/1/wallet/balance",
		binding.Form(walletForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		balanceHandler)
	m.Get("/1/wallet/newaddr",
		binding.Form(walletForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		newAddrHandler)
	m.Post("/1/wallet/send",
		binding.Json(txForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		txHandler)
	m.Get("/1/wallet/txs",
		binding.Form(addrTxsForm{}),
		addrTxsHandler)
}
func PutRequestNoAuth(method string, route string, handler martini.Handler, body io.Reader, params martini.Params, skeleton interface{}) *httptest.ResponseRecorder {
	r.Put(route, binding.Json(skeleton), handler)
	request, _ := http.NewRequest(method, route, body)
	request.Header.Set("Content-Type", "application/json")
	response = httptest.NewRecorder()
	m.ServeHTTP(response, request)
	return response
} // func
Exemple #20
0
func setup(router martini.Router) {
	router.Get("/user/:id", controllers.UserGet)

	router.Put("/user/:id",
		binding.Json(models.User{}),
		binding.ErrorHandler,
		controllers.UserPut)
}
Exemple #21
0
func (s *server) Run(env Env) {
	m := martini.Classic()

	// Setup middleware
	m.Use(secure_handler())
	if env["MARTINI_ENV"] == "production" {
		m.Use(new_relic_handler(env))
	}
	m.Use(gzip_handler())
	m.Use(render_handler())

	m.Get("/", s.IndexHandler)

	m.Post("/api/trips", binding.Json(credentials{}), s.TripsAPI)
	m.Post("/api/stats", binding.Json(credentials{}), s.StatsAPI)

	m.Run()
}
Exemple #22
0
func main() {
	envy.Bootstrap()

	app := martini.Classic()

	app.Map(config.DB())

	app.Use(render.Renderer())

	app.Group("/products", func(router martini.Router) {
		router.Post("", binding.Json(models.Product{}), controllers.ProductsCreate)
		router.Delete("/:id", controllers.ProductsDelete)
		router.Get("", controllers.ProductsIndex)
		router.Get("/:id", controllers.ProductsShow)
		router.Put("/:id", binding.Json(models.Product{}), controllers.ProductsUpdate)
		router.Post("/bulk", binding.Json(models.Products{}), controllers.ProductsBulkCreate)
	}, controllers.ApiAuth())

	app.Run()
}
Exemple #23
0
func (srv *httpServer) setupRoutes() {
	srv.m.Get(`/disco`, srv.getDiscoPage)
	srv.m.Get(`/pusher/info`, srv.getPusherInfo)
	srv.m.Post(`/pusher/**`, srv.createUnknownThing)

	srv.m.Post(`/apps/:app_id/events`, binding.Json(Event{}), srv.createAppEvents)
	srv.m.Get(`/apps/:app_id/channels`, srv.getAppChannels)
	srv.m.Get(`/apps/:app_id/channels/:channel_name`, srv.getAppChannel)
	srv.m.Post(`/apps/:app_id/channels/:channel_name/events`, srv.createAppChannelEvents)
	srv.m.Get(`/apps/:app_id/channels/:channel_name/users`, srv.getAppChannelUsers)
}
Exemple #24
0
Fichier : server.go Projet : jf/gwp
func main() {
	m := martini.Classic()
	m.Use(render.Renderer())

	m.Get("/post/:id", post.Retrieve, post.HandleGet)
	m.Post("/post", binding.Json(post.Post{}), post.HandlePost)
	m.Put("/post/:id", post.Retrieve, post.HandlePut)
	m.Delete("/post/:id", post.Retrieve, post.HandleDelete)
	m.Run()

}
Exemple #25
0
func BindGroupApi(m *martini.ClassicMartini) {
	m.Post("/1/user/joinGroup",
		binding.Json(joinGroupForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		joinGroupHandler)
	m.Post("/1/user/newGroup",
		binding.Json(setGroupForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		setGroupHandler)
	m.Get("/1/user/getGroupInfo",
		binding.Form(groupInfoForm{}),
		ErrorHandler,
		groupInfoHandler)
	m.Get("/1/user/deleteGroup",
		binding.Json(groupDelForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		delGroupHandler)
}
// init runs before everything else.
func init() {
	// Set the API version.
	apiv = "1.05"
	// Check credentials to make sure this is a legit request.
	slackerFile = "slackers.json"
	requestFile = "requests.json"

	configFile = "config.json"
	_, err := os.Stat(configFile)
	// If there is a problem with the file, err on the side of caution and
	// reject the request.
	if err != nil {
		log.Printf("error: Could not find configuration file/%s", configFile)
		os.Exit(1)
	}

	// These are the background processes we need to keep track of.
	InboundList = make(chan SlackMessageIn, 100)
	OutboundList = make(chan SlackMessageOut, 100)
	InboundNotifier = make(chan bool, 1)
	OutboundNotifier = make(chan bool, 1)
	FlushTicker = time.NewTicker(time.Minute * 1)

	// Set up the router.
	m = martini.New()
	// Setup Routes
	r := martini.NewRouter()
	r.Post(`/slack`, binding.Json(SlackMessageIn{}), PushToSlack)
	r.Post(`/slack/config`, binding.Json(SlackConfig{}), AddSlacker)
	r.Put(`/slack/config/:key_id`, binding.Json(SlackConfig{}), UpdateSlacker)
	r.Put(`/slack/config/:key_id/system`, AuthorizeAdmin, MakeSystemSlacker)
	r.Delete(`/slack/config/:key_id`, DeleteSlacker)
	r.Get(`/slack/configs`, GetSlackerCount)
	r.Get(`/slack/request/:email`, RequestSlackerId)
	r.Get(`/slack/requests`, GetRequestCount)
	r.Get(`/slack/ping`, PingTheApi)
	r.Get(`/slack/version`, GetSHPApiVersion)
	// Add the router action
	m.Action(r.Handle)
} // func
Exemple #27
0
// init is called before the application starts.
func init() {

	m := martini.Classic()
	m.Use(render.Renderer())

	m.Use(func(res http.ResponseWriter, req *http.Request) {
		authorization := &spark.Authorization{AccessToken: os.Getenv("SPARK_TOKEN")}
		spark.InitClient(authorization)
		ctx := appengine.NewContext(req)
		spark.SetHttpClient(urlfetch.Client(ctx), ctx)
	})

	m.Post("/spark", binding.Json(SparkEvent{}), func(sparkEvent SparkEvent, res http.ResponseWriter, req *http.Request, r render.Render) {
		ctx := appengine.NewContext(req)
		client := urlfetch.Client(ctx)

		message := spark.Message{ID: sparkEvent.Id}
		message.Get()
		log.Infof(ctx, message.Text)

		if strings.HasPrefix(message.Text, "/") {
			s := strings.Split(sparkEvent.Text, " ")

			command := s[0]
			log.Infof(ctx, "command = %s", command)
			if command == "/routes" {

				resp, _ := client.Get("http://galwaybus.herokuapp.com/routes.json")
				defer resp.Body.Close()
				contents, _ := ioutil.ReadAll(resp.Body)
				log.Infof(ctx, "body = %s\n", contents)

				var routeMap map[string]BusRoute
				json.Unmarshal([]byte(contents), &routeMap)

				text := "Routes:\n\n"
				for _, route := range routeMap {
					text = text + strconv.Itoa(route.Id) + " " + route.LongName + "\n"
				}

				message := spark.Message{
					RoomID: sparkEvent.RoomId,
					Text:   text,
				}
				message.Post()
			}
		}

	})

	http.Handle("/", m)
}
Exemple #28
0
func (bot *TgBot) ServerStartHostPort(uri string, pathl string, host string, port string) {
	if bot.DefaultOptions.RecoverPanic {
		defer func() {
			if r := recover(); r != nil {
				fmt.Printf("There was some panic: %s\n", r)
			}
		}()
	}
	tokendiv := strings.Split(bot.Token, ":")
	if len(tokendiv) != 2 {
		return
	}
	pathl = path.Join(pathl, fmt.Sprintf("%s%s", tokendiv[0], tokendiv[1]))

	if uri != "" {
		puri, err := url.Parse(uri)
		if err != nil {
			fmt.Printf("Bad URL %s", uri)
			return
		}
		nuri, _ := puri.Parse(pathl)

		res, error := bot.SetWebhook(nuri.String())
		if error != nil {
			ec := res.ErrorCode
			fmt.Printf("Error setting the webhook: \nError code: %d\nDescription: %s\n", &ec, res.Description)
			return
		}
	}

	if bot.MainListener == nil {
		bot.StartMainListener()
	}

	m := martini.Classic()
	m.Post(pathl, binding.Json(MessageWithUpdateID{}), func(params martini.Params, msg MessageWithUpdateID) {
		if msg.UpdateID > 0 && msg.Msg.ID > 0 {
			bot.HandleBotan(msg.Msg)
			bot.MainListener <- msg
		}
	})

	if bot.RelicCfg != nil {
		gorelic.InitNewrelicAgent(bot.RelicCfg.Token, bot.RelicCfg.Name, false)
		m.Use(gorelic.Handler)
	}
	if host == "" || port == "" {
		m.Run()
	} else {
		m.RunOnAddr(host + ":" + port)
	}
}
Exemple #29
0
func main() {
	m := martini.Classic()

	// JSON rendering middleware
	m.Use(render.Renderer(render.Options{IndentJSON: true}))

	// puts references all the initialized domain objects in the middleware layer
	m.Use(domain.DomainMiddleware())

	// user routes
	m.Post("/api/v1/users", binding.Json(domain.NewUser{}), binding.ErrorHandler, routes.CreateUser)
	m.Post("/api/v1/authenticate", binding.Json(domain.AuthenticationRequest{}), binding.ErrorHandler, routes.AuthenticateUser)
	m.Get("/api/v1/user", domain.AuthenticationMiddleware, routes.GetAuthenticatedUser) // who am I?!

	// channel routes
	m.Post("/api/v1/channels", domain.AuthenticationMiddleware, binding.Json(domain.Channel{}), binding.ErrorHandler, routes.CreateChannel)
	m.Get("/api/v1/channels", domain.AuthenticationMiddleware, routes.ListChannels)

	// start server
	log.Printf("dogfort starting on %s:%s", os.Getenv("HOST"), os.Getenv("PORT"))
	m.Run()
}
Exemple #30
0
func main() {
	//lol if you don't already use swiftly
	username := os.Getenv("SWIFTLY_AUTH_USER")
	apikey := os.Getenv("SWIFTLY_AUTH_KEY")
	authurl := os.Getenv("SWIFTLY_AUTH_URL")
	region := os.Getenv("SWIFTLY_REGION")
	snet := os.Getenv("SWIFTLY_SNET")
	internal := false
	if strings.ToLower(snet) == "true" {
		internal = true
	}
	//martini looks for a HOST and PORT env var to determine what to listen on
	m := martini.Classic()

	cf := swift.Connection{
		UserName: username,
		ApiKey:   apikey,
		AuthUrl:  authurl,
		Region:   region,
		Internal: internal,
	}
	// Authenticate
	err := cf.Authenticate()
	PanicIf(err)
	m.Map(&cf)

	mc := memcache.New("127.0.0.1:11211")
	m.Map(mc)

	m.Use(render.Renderer())

	m.Get("/", IndexPage)
	m.Get("/history", GetHistory)
	m.Get("/:pasteid", GetPaste)
	m.Get("/:pasteid/:format", GetPaste)
	m.Post("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Put("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Run()
}