Esempio n. 1
0
func startApi(n ApiConfigurationNetwork) {
	apiListener, err := net.Listen("tcp", fmt.Sprintf("%v:%v", n.BindIP, n.BindPort))

	if err != nil {
		panic(err)
	}

	// Adding items:
	goji.Post("/food/add", routeAddFood)

	// Getting items
	goji.Get("/food/get/all", routeGetFoodAll)
	goji.Get("/food/get/id/:id", routeGetFoodById)
	goji.Get("/food/get/date/:year/:month/:day", routeGetFoodByDate)
	// goji.Get("/food/get/name/:name", routeGetFoodByName)

	// Removing items
	goji.Delete("/food/delete/id/:id", routeDeleteFoodById)
	goji.Delete("/food/delete/name/:name", routeDeleteFoodByName)

	// Updating items
	// goji.Put("/food/edit/id/:id", routeUpdateItemById)
	// goji.Put("/food/edit/name/:name", routeUpdateItemByName)

	goji.Get("/food/email/today", routeEmailSendToday)

	goji.ServeListener(apiListener)
}
Esempio n. 2
0
func setupWebRoutes(config *MailServer) {
	goji.Get("/status", func(c web.C, w http.ResponseWriter, r *http.Request) { status(config, c, w, r) })
	goji.Get("/mail", func(c web.C, w http.ResponseWriter, r *http.Request) { allMails(config, c, w, r) })
	goji.Get("/inbox/:email", func(c web.C, w http.ResponseWriter, r *http.Request) { inbox(config, c, w, r) })
	goji.Get("/email/:id", func(c web.C, w http.ResponseWriter, r *http.Request) { mailByID(config, c, w, r) })
	goji.Delete("/inbox/:email", func(c web.C, w http.ResponseWriter, r *http.Request) { deleteMails(config, c, w, r) })
	goji.Delete("/email/:id", func(c web.C, w http.ResponseWriter, r *http.Request) { deleteByID(config, c, w, r) })

}
Esempio n. 3
0
func SetupRoutes() {
	for _, route := range routes {
		for _, method := range route.methods {
			switch method {
			case "GET":
				goji.Get(route.url, route.handler)
				break
			case "POST":
				goji.Post(route.url, route.handler)
				break
			case "PUT":
				goji.Put(route.url, route.handler)
				break
			case "PATCH":
				goji.Patch(route.url, route.handler)
				break
			case "DELETE":
				goji.Delete(route.url, route.handler)
				break
			default:
				goji.Handle(route.url, route.handler)
			}
		}
	}
}
func main() {
	//Profiling
	// go func() {
	// 	log.Println(http.ListenAndServe(":6060", nil))
	// }()

	var (
		config *app.Config
	)

	envParser := env_parser.NewEnvParser()
	envParser.Name(appName)
	envParser.Separator("_")
	envSrc := app.Envs{}
	envParseError := envParser.Map(&envSrc)
	app.Chk(envParseError)

	app.PrintWelcome()

	switch envSrc.Mode {
	case app.MODE_DEV:
		logr.Level = logrus.InfoLevel
	case app.MODE_PROD:
		logr.Level = logrus.WarnLevel
	case app.MODE_DEBUG:
		logr.Level = logrus.DebugLevel
	}

	config = app.NewConfig(envSrc.AssetsUrl, envSrc.UploadPath)

	logFile, fileError := os.OpenFile(envSrc.LogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0660)
	defer logFile.Close()
	if fileError == nil {
		logr.Out = logFile
	} else {
		fmt.Println("invalid log file; \n, Error : ", fileError, "\nopting standard output..")
	}

	redisService, reErr := services.NewRedis(envSrc.RedisUrl)
	reErr = reErr

	sqlConnectionStringFormat := "%s:%s@tcp(%s:%s)/%s"
	sqlConnectionString := fmt.Sprintf(sqlConnectionStringFormat, envSrc.MysqlUser, envSrc.MysqlPassword,
		envSrc.MysqlHost, envSrc.MysqlPort, envSrc.MysqlDbName)
	mySqlService := services.NewMySQL(sqlConnectionString, 10)

	//TODO check
	baseHandler := handlers.NewBaseHandler(logr, config)
	userHandler := handlers.NewUserHandler(baseHandler, redisService, mySqlService)
	reqHandler := handlers.NewRequestHandler(baseHandler, redisService, mySqlService)

	goji.Post("/register", baseHandler.Route(userHandler.DoRegistration))
	goji.Post("/login", baseHandler.Route(userHandler.DoLogin))
	goji.Get("/bloodReq", baseHandler.Route(reqHandler.RemoveBloodRequest))
	goji.Post("/bloodReq", baseHandler.Route(reqHandler.MakeBloodRequest))
	goji.Delete("/bloodReq", baseHandler.Route(reqHandler.RemoveBloodRequest))
	goji.NotFound(baseHandler.NotFound)

	goji.Serve()
}
Esempio n. 5
0
func (s *GossamerServer) Start() {
	goji.Get("/", s.HandleWebUiIndex)
	goji.Get("/things.html", s.HandleWebUiThings)
	goji.Get("/sensors.html", s.HandleWebUiSensors)
	goji.Get("/observations.html", s.HandleWebUiObservations)
	goji.Get("/observedproperties.html", s.HandleWebUiObservedProperties)
	goji.Get("/locations.html", s.HandleWebUiLocations)
	goji.Get("/datastreams.html", s.HandleWebUiDatastreams)
	goji.Get("/featuresofinterest.html", s.HandleWebUiFeaturesOfInterest)
	goji.Get("/historiclocations.html", s.HandleWebUiHistoricLocations)
	goji.Get("/css/*", s.HandleWebUiResources)
	goji.Get("/img/*", s.HandleWebUiResources)
	goji.Get("/js/*", s.HandleWebUiResources)

	goji.Get("/v1.0", s.handleRootResource)
	goji.Get("/v1.0/", s.handleRootResource)

	goji.Get("/v1.0/*", s.HandleGet)
	goji.Post("/v1.0/*", s.HandlePost)
	goji.Put("/v1.0/*", s.HandlePut)
	goji.Delete("/v1.0/*", s.HandleDelete)
	goji.Patch("/v1.0/*", s.HandlePatch)

	flag.Set("bind", ":"+strconv.Itoa(s.port))

	log.Println("Start Server on port ", s.port)
	goji.Serve()
}
Esempio n. 6
0
File: main.go Progetto: t2y/misc
func main() {
	Logger.Formatter = new(logrus.JSONFormatter)

	// init
	db := InitDatabase("./myapp.db")
	defer db.Close()

	// middleware
	goji.Use(func(c *web.C, h http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			c.Env["DB"] = db
			h.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)

	})
	goji.Use(glogrus.NewGlogrus(Logger, "myapp"))
	goji.Use(middleware.Recoverer)
	goji.Use(middleware.NoCache)
	goji.Use(SetProperties)

	// handlers
	goji.Get("/users/", ListUsers)
	goji.Get(regexp.MustCompile(`/users/(?P<name>\w+)$`), GetUser)
	goji.Get("/*", AllMatchHandler)
	goji.Post(regexp.MustCompile(`/users/(?P<name>\w+)$`), RegisterUser)
	goji.Put("/users/:name", UpdateUserInfo)
	goji.Delete("/users/:name", DeleteUserInfo)

	goji.Serve()
}
Esempio n. 7
0
func main() {
	var cfg Config
	stderrBackend := logging.NewLogBackend(os.Stderr, "", 0)
	stderrFormatter := logging.NewBackendFormatter(stderrBackend, stdout_log_format)
	logging.SetBackend(stderrFormatter)
	logging.SetFormatter(stdout_log_format)

	if cfg.ListenAddr == "" {
		cfg.ListenAddr = "127.0.0.1:63636"
	}
	flag.Set("bind", cfg.ListenAddr)
	log.Info("Starting app")
	log.Debug("version: %s", version)

	webApp := webapi.New()
	goji.Get("/dns", webApp.Dns)
	goji.Post("/dns", webApp.Dns)
	goji.Get("/isItWorking", webApp.Healthcheck)

	goji.Post("/redir/batch", webApp.BatchAddRedir)
	goji.Post("/redir/:from/:to", webApp.AddRedir)
	goji.Delete("/redir/:from", webApp.DeleteRedir)
	goji.Get("/redir/list", webApp.ListRedir)

	//_, _ = api.New(api.CallbackList{})

	goji.Serve()
}
Esempio n. 8
0
func initServer(conf *configuration.Configuration, conn *zk.Conn, eventBus *event_bus.EventBus) {
	stateAPI := api.StateAPI{Config: conf, Zookeeper: conn}
	serviceAPI := api.ServiceAPI{Config: conf, Zookeeper: conn}
	eventSubAPI := api.EventSubscriptionAPI{Conf: conf, EventBus: eventBus}

	conf.StatsD.Increment(1.0, "restart", 1)
	// Status live information
	goji.Get("/status", api.HandleStatus)

	// State API
	goji.Get("/api/state", stateAPI.Get)

	// Service API
	goji.Get("/api/services", serviceAPI.All)
	goji.Post("/api/services", serviceAPI.Create)
	goji.Put("/api/services/:id", serviceAPI.Put)
	goji.Delete("/api/services/:id", serviceAPI.Delete)

	goji.Post("/api/marathon/event_callback", eventSubAPI.Callback)

	// Static pages
	goji.Get("/*", http.FileServer(http.Dir("./webapp")))

	registerMarathonEvent(conf)

	goji.Serve()
}
Esempio n. 9
0
func routing() {

	///// Website /////

	goji.Get("/", Index)

	/////API///////

	//inscription
	goji.Post("/api/signup", Signup)

	//connexion
	goji.Post("/api/signin", Signin)

	//creation de poste
	goji.Post("/api/post", CreatePost)

	//obtenir ses propres posts
	goji.Get("/api/post", GetOwnPosts)

	//obtenir un post par son id
	goji.Get("/api/post/:id", GetPost)

	//obtenir une liste de post par le login
	goji.Get("/api/:login/post", GetUserPosts)

	//suppresion d'un poste
	goji.Delete("/api/post/:id", DeletePost)

	//comfirmation de l'email si le fichier app.json est configuré pour
	if models.Conf.Status == "prod" || models.Conf.EmailCheck == true {
		goji.Get("/comfirmation", Comfirmation)
	}
}
Esempio n. 10
0
func main() {
	goji.Get("/recipes/:id", getRecipes)
	goji.Get("/recipes", getAllRecipes)
	goji.Delete("/recipes/:id", deleteRecipe)
	goji.Put("/recipes", putRecipe)

	goji.Serve()
}
Esempio n. 11
0
func InitRoutes() {
	goji.Get("/users", UserList)
	goji.Get("/users/:id", UserView)
	goji.Delete("/users/:id", UserDelete)
	goji.Post("/users", UserCreate)
	goji.Put("/users/:id", UserUpdate)
	goji.Get("/", Index)
}
Esempio n. 12
0
func main() {
	goji.Get("/todo", todos)
	goji.Post("/todo/newTodo", newTodo)
	goji.Get("/todo:id", getTodo)
	goji.Put("/todo:id", putTodo)
	goji.Delete("/todo:id", delTodo)
	goji.Serve()
}
Esempio n. 13
0
File: server.go Progetto: jf/gwp
func main() {
	goji.Get("/post/:id", post.HandleGet)
	goji.Post("/post", post.HandlePost)
	goji.Put("/post/:id", post.HandlePut)
	goji.Delete("/post/:id", post.HandleDelete)
	goji.Serve()

}
Esempio n. 14
0
func main() {
	// HTTP Handlers
	goji.Post("/:topic_name", publishingHandler)
	goji.Post("/:topic_name/:subscriber_name", subscribingHandler)
	goji.Delete("/:topic_name/:subscriber_name", unsubscribingHandler)
	goji.Get("/:topic_name/:subscriber_name", pollingHandler)

	// Serve on the default :8000 port.
	goji.Serve()
}
Esempio n. 15
0
func defineHandlers() {
	pref := "/rest/:service/:region"
	goji.Get(pref+"/:resource", indexHandler)
	goji.Get(pref+"/:resource/:id", showHandler)
	goji.Put(pref+"/:resource/:id", updateHandler)
	goji.Post(pref+"/:resource", createHandler)
	goji.Delete(pref+"/:resource/:id", deleteHandler)
	goji.Post(pref+"/action/:action", serviceActionHandler)
	goji.Post(pref+"/:resource/action/:action", collectionActionHandler)
	goji.Post(pref+"/:resource/:id/action/:action", resourceActionHandler)
}
Esempio n. 16
0
func main() {
	goji.Get("/", index)
	goji.Get("/assets/*", http.FileServer(http.Dir("./dist")))
	goji.Get("/api/todos", todos)
	goji.Post("/api/todos", newTodo)
	goji.Put("/api/todos/:id", putTodo)
	goji.Delete("/api/todos/:id", delTodo)

	goji.NotFound(index)

	goji.Serve()
}
Esempio n. 17
0
func main() {
	//cross browser origin
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{"GET", "POST", "DELETE"},
	})

	//routing
	goji.Use(c.Handler)
	goji.Get("/friend/", get)
	goji.Post("/friend/:name", post)
	goji.Delete("/friend/:name", delete)
	goji.Serve()
}
Esempio n. 18
0
func routing() {
	//inscription
	goji.Post("/api/signup", Signup)

	//connexion
	goji.Post("/api/signin", Signin)

	//delete session
	goji.Delete("/api/session/destroy", Logout)

	if models.Conf.Status == "prod" || models.Conf.EmailCheck == true {
		//comfirmation de l'email si le fichier app.json est configuré pour
		goji.Get("/comfirmation", Comfirmation)
	}
}
Esempio n. 19
0
func main() {

	controller, error := controller.NewController()
	if error != nil {
		log.Fatal(error)
	}

	controller.StartPush()
	defer controller.Close()

	goji.Post(userURLPath, controller.RegisterUser)
	goji.Get(userURLPath+userPlaceholder, controller.RegisteredUser)
	goji.Delete(userURLPath+userPlaceholder, controller.UnregisterUser)

	goji.Serve()
}
Esempio n. 20
0
func main() {
	// Construct the dsn used for the database
	dsn := os.Getenv("RYTSAR_DB_USER") + ":" + os.Getenv("RYTSAR_DB_PASS") + "@tcp(" + os.Getenv("RYTSAR_DB_HOST") + ":" + os.Getenv("RYTSAR_DB_PORT") + ")/" + os.Getenv("RYTSAR_DB_NAME")

	// Construct a new AccessorGroup and connects it to the database
	ag := new(accessors.AccessorGroup)
	ag.ConnectToDB("mysql", dsn)

	// Constructs a new ControllerGroup and gives it the AccessorGroup
	cg := new(controllers.ControllerGroup)
	cg.Accessors = ag

	goji.Get("/health", cg.Health) // Service health
	goji.Get("/database/:latitude/:longitude/:radius", cg.DumpDatabase)
	goji.Get("/count/:latitude/:longitude/:radius", cg.CountNearbyEnemies)
	goji.Delete("/delete/:id", cg.DeleteEnemy)
	goji.Serve()
}
Esempio n. 21
0
func setup() {
	goji.Use(ContentSecurityPolicy(CSPOptions{
		policy: Config.contentSecurityPolicy,
		frame:  Config.xFrameOptions,
	}))

	if Config.noLogs {
		goji.Abandon(middleware.Logger)
	}

	// make directories if needed
	err := os.MkdirAll(Config.filesDir, 0755)
	if err != nil {
		log.Fatal("Could not create files directory:", err)
	}

	err = os.MkdirAll(Config.metaDir, 0700)
	if err != nil {
		log.Fatal("Could not create metadata directory:", err)
	}

	// ensure siteURL ends wth '/'
	if lastChar := Config.siteURL[len(Config.siteURL)-1:]; lastChar != "/" {
		Config.siteURL = Config.siteURL + "/"
	}

	// Template setup
	p2l, err := NewPongo2TemplatesLoader()
	if err != nil {
		log.Fatal("Error: could not load templates", err)
	}
	TemplateSet := pongo2.NewSet("templates", p2l)
	TemplateSet.Globals["sitename"] = Config.siteName
	err = populateTemplatesMap(TemplateSet, Templates)
	if err != nil {
		log.Fatal("Error: could not load templates", err)
	}

	staticBox = rice.MustFindBox("static")
	timeStarted = time.Now()
	timeStartedStr = strconv.FormatInt(timeStarted.Unix(), 10)

	// Routing setup
	nameRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)$`)
	selifRe := regexp.MustCompile(`^/selif/(?P<name>[a-z0-9-\.]+)$`)
	selifIndexRe := regexp.MustCompile(`^/selif/$`)
	torrentRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)/torrent$`)

	goji.Get("/", indexHandler)
	goji.Get("/paste/", pasteHandler)
	goji.Get("/paste", http.RedirectHandler("/paste/", 301))

	if Config.remoteUploads {
		goji.Get("/upload", uploadRemote)
		goji.Get("/upload/", uploadRemote)
	}

	goji.Post("/upload", uploadPostHandler)
	goji.Post("/upload/", uploadPostHandler)
	goji.Put("/upload", uploadPutHandler)
	goji.Put("/upload/:name", uploadPutHandler)
	goji.Delete("/:name", deleteHandler)

	goji.Get("/static/*", staticHandler)
	goji.Get("/favicon.ico", staticHandler)
	goji.Get("/robots.txt", staticHandler)
	goji.Get(nameRe, fileDisplayHandler)
	goji.Get(selifRe, fileServeHandler)
	goji.Get(selifIndexRe, unauthorizedHandler)
	goji.Get(torrentRe, fileTorrentHandler)
	goji.NotFound(notFoundHandler)
}
Esempio n. 22
0
func serveGoji() {
	goji.Get("/fs/[a-zA-Z0-9._/-]+", httpfs.HandleGet)
	goji.Put("/fs/[a-zA-Z0-9._/-]+", httpfs.HandlePut)
	goji.Delete("/fs/[a-zA-Z0-9._/-]+", httpfs.HandleDelete)
	goji.ServeListener(bind.Socket(":10002"))
}
Esempio n. 23
0
func main() {
	//
	// Event queue hadling
	//
	err := players.StartEventProcessor()
	if err != nil {
		fmt.Printf("%+v", err.Error)
		println("Could not initialize event queue. Exiting")
		os.Exit(1)
	}

	//
	// HTTP Serving
	//
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"*"},
		AllowedMethods: []string{"GET", "PUT", "PATCH", "POST", "OPTIONS", "DELETE"},
	})
	goji.Use(c.Handler)
	goji.Use(middleware.TokenHandler)

	goji.Post("/login", appHandler(login))

	goji.Get("/players", appHandler(listAllPlayers))
	goji.Post("/players", appHandler(createNewPlayer))
	goji.Get("/players/quotes", appHandler(getAllPlayerQuotes))
	goji.Get("/players/:uuid", appHandler(getPlayer))
	goji.Put("/players/:uuid", appHandler(updatePlayer))
	goji.Post("/players/:uuid/quotes", appHandler(addPlayerQuote))
	goji.Get("/players/:uuid/profile", appHandler(getPlayerProfile))
	goji.Put("/players/:uuid/profile", appHandler(updatePlayerProfile))
	goji.Get("/players/:uuid/user", appHandler(getUserForPlayer))
	goji.Put("/players/:uuid/user", appHandler(setUserForPlayer))
	goji.Put("/players/:uuid/user/password", appHandler(setUserPassword))
	goji.Put("/players/:uuid/user/settings", appHandler(setUserSettings))
	goji.Put("/players/:uuid/user/admin", appHandler(setUserAdmin))
	goji.Put("/players/:uuid/gossip", appHandler(setPlayerGossip))
	goji.Patch("/players/:uuid/gossip", appHandler(setPlayerGossip))
	goji.Delete("/players/:uuid/gossip", appHandler(resetPlayerGossip))
	goji.Get("/players/:uuid/debts", appHandler(showPlayerDebt))
	goji.Delete("/players/:uuid/debts", appHandler(resetPlayerDebts))
	goji.Get("/players/:uuid/credits", appHandler(showPlayerCredits))
	goji.Post("/players/:uuid/debts", appHandler(addPlayerDebt))
	goji.Delete("/players/:uuid/debts/:debtuuid", appHandler(settlePlayerDebt))
	goji.Put("/players/:uuid/votes", appHandler(setPlayerVotes))
	goji.Patch("/players/:uuid/votes", appHandler(setPlayerVotes))
	goji.Post("/players/notification_test", appHandler(testPlayerNotify))

	goji.Post("/users", appHandler(createNewUser))

	goji.Get("/locations", appHandler(listAllLocations))
	goji.Post("/locations", appHandler(createNewLocation))
	goji.Get("/locations/:uuid", appHandler(getLocation))
	goji.Put("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Patch("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Post("/locations/:uuid/pictures", appHandler(addLocationPicture))

	goji.Get("/tournaments", appHandler(listAllTournaments))
	goji.Post("/tournaments", appHandler(createNewTournament))
	goji.Get("/tournaments/:uuid", appHandler(getTournament))
	goji.Put("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Patch("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Put("/tournaments/:uuid/played", appHandler(setTournamentPlayed))
	goji.Get("/tournaments/:uuid/result", appHandler(getTournamentResult))
	goji.Put("/tournaments/:uuid/result", appHandler(setTournamentResult))
	goji.Post("/tournaments/:uuid/noshows", appHandler(addTournamentNoShow))
	goji.Delete("/tournaments/:uuid/noshows/:playeruuid", appHandler(removeTournamentNoShow))

	goji.Get("/seasons", appHandler(listAllSeasons))
	goji.Get("/seasons/stats", appHandler(getTotalStats))
	goji.Get("/seasons/standings", appHandler(getTotalStandings))
	goji.Get("/seasons/titles", appHandler(getTotalTitles))
	goji.Get("/seasons/:year/tournaments", appHandler(listTournamentsBySeason))
	goji.Get("/seasons/:year/standings", appHandler(getSeasonStandings))
	goji.Get("/seasons/:year/titles", appHandler(getSeasonTitles))
	goji.Get("/seasons/:year/stats", appHandler(getSeasonStats))

	goji.Get("/caterings", appHandler(listAllCaterings))
	goji.Post("/caterings", appHandler(createNewCatering))
	goji.Get("/caterings/:uuid", appHandler(getCatering))
	goji.Put("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Patch("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Post("/caterings/:uuid/votes", appHandler(addCateringVote))
	goji.Put("/caterings/:uuid/votes/:playeruuid", appHandler(updateCateringVote))

	goji.Get("/news", appHandler(listAllNews))
	goji.Get("/news/:uuid", appHandler(getNewsItem))
	goji.Patch("/news/:uuid", appHandler(updateNewsItem))
	goji.Post("/news", appHandler(createNewNewsItem))
	goji.Post("/news/:uuid/comments", appHandler(addNewsComment))
	// TODO: Comment updates/deletion

	goji.Serve()
}
Esempio n. 24
0
func main() {
	//init DB user and DB logging
	gest.Db = InitDbUser()
	//close all db at end of program
	//defer gest.Db.Close()

	defer gest.Db.Close()

	//DbCreateUser(gest.Db)
	DbCreateUser(gest.Db)

	// START ROUTING API //

	//this is just a try to show it work :)
	goji.Get("/api", IndexShit)

	goji.Post("/api/session/create", CreateSession)

	goji.Post("/api/user/create", CreateProfile)

	goji.Get("/api/user/profile/me", MyProfile)
	goji.Get("/api/user/profile/:login", GetProfile)
	goji.Put("/api/user/profile/password", EditPassword)
	goji.Put("/api/user/profile/login", EditLogin)
	goji.Put("/api/user/profile/email", EditEmail)
	goji.Put("/api/user/profile/name", EditName)
	goji.Put("/api/user/profile/bio", EditBio)
	goji.Put("/api/user/profile/orientation", EditOrientation)
	goji.Put("/api/user/profile/birth_date", EditBirthDate)

	goji.Get("/api/exist/:login", IsUserExist)

	goji.Get("/api/user/block", ListBlock)

	goji.Post("/api/user/block/:login", BlockUser)
	goji.Delete("/api/user/block/:login", UnblockUser)

	goji.Post("/api/user/report/:login", ReportUser)

	goji.Post("/api/user/tag", AddTag)
	goji.Get("/api/user/tag/:login", ListTag)
	goji.Delete("/api/user/tag/:id", DeleteTag)

	goji.Post("/api/user/image", AddImage)
	goji.Get("/api/user/image", ListImage)
	goji.Delete("/api/user/image/:id", DelImage)

	goji.Get("/api/user/like", Likes)
	goji.Post("/api/user/like/:login", Like)
	goji.Delete("/api/user/like/:login", DelLike)

	goji.Get("/api/user/match", MyMatchs)

	goji.Get("/api/user/history", GetVisiteHistory)

	goji.Get("/api/user/message/:login", GetMessage)
	goji.Post("/api/user/message/:login", SendMessage)

	goji.Get("/api/user/notifications", GetNotification)
	goji.Get("/api/user/nbnotifications", GetNbNotification)

	//END OF ROUTING API//

	//Start of web version//
	goji.Get("/page1", Hihi)
	goji.Get("/page2", Hihi)
	goji.Get("/", Hihi)

	goji.Get("/assets/*", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets"))))
	goji.Get("/Images/*", http.StripPrefix("/Images/", http.FileServer(http.Dir("./Images"))))
	goji.Serve()
}
Esempio n. 25
0
func serve(c *cli.Context) {
	client := c.String("consuladdress")
	name := c.String("name")

	// Initialize a new store with consul
	kv, err := libkv.NewStore(
		store.CONSUL, // or "consul"
		[]string{client},
		&store.Config{
			ConnectionTimeout: 10 * time.Second,
		},
	)
	if err != nil {
		log.Fatal("Cannot create store consul")
	}

	prefix := "app/port-authority/config"
	key_apiport := fmt.Sprintf("%s/api_port", prefix)
	//key_uiport := fmt.Sprintf("%s/ui_port", prefix)
	key_rpcport := fmt.Sprintf("%s/rpc_port", prefix)
	key_templatedir := fmt.Sprintf("%s/template_directory", prefix)
	key_airbrakeapikey := fmt.Sprintf("%s/airbrake/api_key", prefix)
	key_airbrakeendpoint := fmt.Sprintf("%s/airbrake/endpoint", prefix)
	havestore := true
	tmp, err := kv.Get(key_apiport)
	if err != nil {
		havestore = false
		log.Printf("Error: %v", err)
	} else {
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s/api_port", prefix)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			port, err := strconv.Atoi(string(tmp.Value))
			if err != nil {
				config.Port = int(port)
			}
		}
	}
	var port_start = 30000
	var port_end = 40000
	if havestore {
		//config.RPCPort, err = kv.Get(key_rpcport)
		log.Printf("Connected to config store")
		tmp, err = kv.Get(key_templatedir)
		if err != nil {
			log.Print("template_directory key not foumd, using /tmp as default!")
			config.TemplateDirectory = "/tmp"
		} else {
			config.TemplateDirectory = string(tmp.Value)
		}

		tmp, err = kv.Get(key_rpcport)
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s/rpc_port", prefix)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			fmt.Printf("rpcport: %s", string(tmp.Value))
			port, err := strconv.Atoi(string(tmp.Value))
			log.Printf("%s %v", port, err)
			if err != nil {
				config.RPCPort = int(port)
			}
		}
		var my_key string
		if name != "" {
			my_key = fmt.Sprintf("%s/%s", prefix, name)
		} else {
			my_key = prefix
		}

		key_portstart := fmt.Sprintf("%s/ports_begin", my_key)
		tmp, err = kv.Get(key_portstart)
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s", key_portstart)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			port, err := strconv.Atoi(string(tmp.Value))
			if err == nil {
				port_start = int(port)
			}
		}

		key_portend := fmt.Sprintf("%s/ports_end", my_key)
		tmp, err = kv.Get(key_portend)
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s", key_portend)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			port, err := strconv.Atoi(string(tmp.Value))
			if err == nil {
				port_end = int(port)
			}
		}
	}
	if actions.InitializeRedisClient("127.0.0.1:6379", "") != nil {
		log.Fatal("Can not connect to Redis!")
	}
	log.Printf("Initializing with ports from %d to %d", port_start, port_end)
	err = actions.InitializePorts(port_start, port_end)
	if err != nil {
		if strings.Contains(err.Error(), "already been init") {
			log.Print(err.Error())
		} else {
			log.Printf("Error on init: %v", err)
		}
	}

	if len(config.BindAddress) != 0 {
		flag.Set("bind", config.BindAddress)
	}
	if config.Port == 0 {
		log.Print("ENV contained no port, using default")
		config.Port = 8080
		flag.Set("bind", fmt.Sprintf("%s:%d", config.BindAddress, config.Port))
	}
	if config.RPCPort == 0 {
		config.RPCPort = config.Port + 1
	}

	if config.TemplateDirectory > "" {
		if !strings.HasSuffix(config.TemplateDirectory, "/") {
			config.TemplateDirectory += "/"
		}
	}
	handlers.TemplateBase = config.TemplateDirectory

	config_json, _ := json.Marshal(config)
	if havestore {
		keypair, err := kv.Get(key_airbrakeapikey)
		abendpoint, err := kv.Get(key_airbrakeendpoint)
		if err == nil {
			key := keypair.Value
			//airbrake.Endpoint = "https://api.airbrake.io/notifier_api/v2/notices"
			airbrake.Endpoint = string(abendpoint.Value)
			airbrake.ApiKey = string(key)
			airbrake.Environment = os.Getenv("RVT_ENVIRONMENT")
			if len(airbrake.Environment) == 0 {
				airbrake.Environment = "Development"
			}
		}
	}
	log.Printf("Config: %s", config_json)
	// HTML Interface URLS
	// API URLS
	goji.Put("/api/service/:id", handlers.APIGetOpenPort)
	goji.Get("/api/service/:id", handlers.APIGetPortFromInstance)
	goji.Delete("/api/service/:id", handlers.APIRemoveService)
	goji.Get("/api/port/:port", handlers.APIGetInstanceFromPort)
	goji.Get("/api/ports/inventory/count", handlers.APIGetPortCapacity)
	goji.Get("/api/ports/inventory/list", handlers.APIGetAvailableInventory)
	goji.Get("/api/ports/assigned/count", handlers.APIGetAssignedCount)
	goji.Get("/api/ports/assigned/list", handlers.APIGetAssignedList)
	goji.Serve()
}
Esempio n. 26
0
func main() {
	var (
		dburl  = os.Getenv("MONGODB_URL")
		dbname = os.Getenv("MONGODB_NAME")
	)

	if len(dburl) == 0 {
		dburl = DEFAULT_DB_URL
	}

	if len(dbname) == 0 {
		dbname = DEFAULT_DB_NAME
	}

	mdb := NewMongoDB(dburl, dbname)
	defer mdb.session.Close()

	mdb.session.DB(mdb.name).C("tokens").EnsureIndex(mgo.Index{
		Key: []string{"secret", "user_id"},
	})

	mdb.session.DB(mdb.name).C("boards").EnsureIndex(mgo.Index{
		Key: []string{"members.user_id"},
	})

	mdb.session.DB(mdb.name).C("tokens").EnsureIndex(mgo.Index{
		Key: []string{"board_id"},
	})

	goji.Get("/users",
		GetUsers)
	goji.Get("/users/:user_id",
		GetUser)

	goji.Get("/boards",
		GetBoards)
	goji.Get("/boards/:board_id",
		GetBoard)
	goji.Get("/boards/:board_id/members",
		GetMembers)
	goji.Get("/boards/:board_id/tickets",
		GetTickets)

	goji.Post("/boards",
		AddBoard)
	goji.Post("/boards/:board_id/members",
		AddMember)
	goji.Post("/boards/:board_id/tickets",
		AddTicket)

	goji.Delete("/boards/:board_id",
		RemoveBoard)
	goji.Delete("/boards/:board_id/members/:member_id",
		RemoveMember)
	goji.Delete("/boards/:board_id/tickets/:ticket_id",
		RemoveTicket)

	goji.Put("/boards/:board_id",
		UpdateBoard)
	goji.Put("/boards/:board_id/size",
		UpdateBoardSize)
	goji.Put("/boards/:board_id/members/:member_id",
		UpdateBoardMember)
	goji.Put("/boards/:board_id/tickets/:ticket_id",
		UpdateTicket)
	goji.Put("/boards/:board_id/tickets/:ticket_id/position",
		UpdateTicketPosition)

	goji.Use(mdb.Middleware)
	goji.Use(authenticate)

	goji.Serve()
	return
}
Esempio n. 27
0
func (mux *Mux) Delete(pattern web.PatternType, h handler) {
	goji.Delete(pattern, func(c web.C, w http.ResponseWriter, r *http.Request) {
		mux.handleRequest(c, w, r, h)
	})
}
Esempio n. 28
0
func (ctr *Controller) RouteDelete(rt *Route) {
	goji.Delete(rt.Pattern, handlerWrap(rt))
}
Esempio n. 29
0
func main() {
	mc, err := actions.GetConstellation(config.Name, config.SentinelConfigFile, config.GroupName, config.SentinelHostAddress)
	if err != nil {
		log.Fatal("Unable to connect to constellation")
	}
	//log.Print("Starting refresh ticker")

	// Try to set to the IP the sentinel is bound do
	//flag.Set("bind", mc.SentinelConfig.Host+":8000")

	//go RefreshData()
	_, _ = mc.GetPodMap()
	//for _, pod := range pm {
	//handlers.NodeMaster.AddNode(pod.Master)
	//for _, node := range pod.Nodes { handlers.NodeMaster.AddNode(&node) }
	//}
	mc.IsBalanced()
	handlers.ManagedConstellation = mc
	_ = handlers.NewPageContext()
	if handlers.ManagedConstellation.AuthCache == nil {
		log.Print("Uninitialized AuthCache, StartCache not called, calling now")
		handlers.ManagedConstellation.StartCache()
	}
	log.Printf("Main Cache Stats: %+v", handlers.ManagedConstellation.AuthCache.GetStats())
	log.Printf("Hot Cache Stats: %+v", handlers.ManagedConstellation.AuthCache.GetHotStats())
	//log.Printf("MC:%+v", handlers.ManagedConstellation)

	// HTML Interface URLS
	goji.Get("/constellation/", handlers.ConstellationInfoHTML) // Needs moved? instance tree?
	goji.Get("/dashboard/", handlers.Dashboard)                 // Needs moved? instance tree?
	goji.Get("/constellation/addpodform/", handlers.AddPodForm)
	goji.Post("/constellation/addpod/", handlers.AddPodHTML)
	goji.Post("/constellation/addsentinel/", handlers.AddSentinelHTML)
	goji.Get("/constellation/addsentinelform/", handlers.AddSentinelForm)
	goji.Get("/constellation/rebalance/", handlers.RebalanceHTML)
	//goji.Get("/pod/:podName/dropslave", handlers.DropSlaveHTML)
	goji.Get("/pod/:podName/addslave", handlers.AddSlaveHTML)
	goji.Post("/pod/:podName/addslave", handlers.AddSlaveHTMLProcessor)
	goji.Post("/pod/:name/failover", handlers.DoFailoverHTML)
	goji.Post("/pod/:name/reset", handlers.ResetPodProcessor)
	goji.Post("/pod/:name/balance", handlers.BalancePodProcessor)
	goji.Get("/pod/:podName", handlers.ShowPod)
	goji.Get("/pods/", handlers.ShowPods)
	goji.Get("/nodes/", handlers.ShowNodes)
	goji.Get("/node/:name", handlers.ShowNode)
	goji.Get("/", handlers.Root) // Needs moved? instance tree?

	// API URLS
	goji.Get("/api/knownpods", handlers.APIGetPods)
	goji.Put("/api/monitor/:podName", handlers.APIMonitorPod)
	goji.Post("/api/constellation/:podName/failover", handlers.APIFailover)

	goji.Get("/api/pod/:podName", handlers.APIGetPod)
	goji.Put("/api/pod/:podName", handlers.APIMonitorPod)
	goji.Put("/api/pod/:podName/addslave", handlers.APIAddSlave)
	goji.Delete("/api/pod/:podName", handlers.APIRemovePod)
	goji.Get("/api/pod/:podName/master", handlers.APIGetMaster)
	goji.Get("/api/pod/:podName/slaves", handlers.APIGetSlaves)

	goji.Post("/api/node/clone", handlers.Clone) // Needs moved to the node tree
	goji.Get("/api/node/:name", handlers.GetNodeJSON)

	goji.Get("/static/*", handlers.Static) // Needs moved? instance tree?
	//goji.Abandon(middleware.Logger)

	goji.Serve()

}