func main() {
	flag.StringVar(&repoPrefix, "prefix", "", "The repo name prefix required in order to build.")
	flag.Parse()

	if repoPrefix == "" {
		log.Fatal("Specify a prefix to look for in the repo names with -prefix='name'")
	}

	if f, err := os.Stat(sourceBase); f == nil || os.IsNotExist(err) {
		log.Fatalf("The -src folder, %s, doesn't exist.", sourceBase)
	}

	if f, err := os.Stat(destBase); f == nil || os.IsNotExist(err) {
		log.Fatalf("The -dest folder, %s, doesn't exist.", destBase)
	}

	if dbConnString != "" {
		InitDatabase()
	}

	goji.Get("/", buildsIndexHandler)
	goji.Get("/:name/:repo_tag", buildsShowHandler)
	goji.Post("/_github", postReceiveHook)
	goji.Serve()
}
Example #2
0
func main() {
	// Construct the dsn used for the database
	dsn := os.Getenv("DATABASE_USERNAME") + ":" + os.Getenv("DATABASE_PASSWORD") + "@tcp(" + os.Getenv("DATABASE_HOST") + ":" + os.Getenv("DATABASE_PORT") + ")/" + os.Getenv("DATABASE_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

	c := cron.New()
	c.AddFunc("0 0 20 * * 1-5", func() { // Run at 2:00pm MST (which is 21:00 UTC) Monday through Friday
		helpers.Webhook(helpers.ReportLeaders(ag))
	})
	c.Start()

	goji.Get("/health", cg.Health)
	goji.Get("/leaderboard", cg.ReportLeaders)
	goji.Post("/slack", cg.Slack) // The main endpoint that Slack hits
	goji.Post("/play", cg.User)
	goji.Post("/portfolio", cg.Portfolio)
	goji.Get("/check/:symbol", cg.Check)
	goji.Post("/buy/:quantity/:symbol", cg.Buy)
	goji.Post("/sell/:quantity/:symbol", cg.Sell)
	goji.Serve()
}
Example #3
0
func (a *App) Serve() {
	requestHandlers := &handlers.RequestHandler{
		Config:               &a.config,
		Horizon:              a.horizon,
		TransactionSubmitter: a.transactionSubmitter,
	}

	portString := fmt.Sprintf(":%d", *a.config.Port)
	flag.Set("bind", portString)

	goji.Abandon(middleware.Logger)
	goji.Use(handlers.StripTrailingSlashMiddleware())
	goji.Use(handlers.HeadersMiddleware())
	if a.config.ApiKey != "" {
		goji.Use(handlers.ApiKeyMiddleware(a.config.ApiKey))
	}

	if a.config.Accounts.AuthorizingSeed != nil {
		goji.Post("/authorize", requestHandlers.Authorize)
	} else {
		log.Warning("accounts.authorizing_seed not provided. /authorize endpoint will not be available.")
	}

	if a.config.Accounts.IssuingSeed != nil {
		goji.Post("/send", requestHandlers.Send)
	} else {
		log.Warning("accounts.issuing_seed not provided. /send endpoint will not be available.")
	}

	goji.Post("/payment", requestHandlers.Payment)
	goji.Serve()
}
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()
}
Example #5
0
func main() {
	// Initalize database.
	ExecuteSchemas()
	// Serve static files.
	staticDirs := []string{"bower_components", "res"}
	for _, d := range staticDirs {
		static := web.New()
		pattern, prefix := fmt.Sprintf("/%s/*", d), fmt.Sprintf("/%s/", d)
		static.Get(pattern, http.StripPrefix(prefix, http.FileServer(http.Dir(d))))
		http.Handle(prefix, static)
	}

	goji.Use(applySessions)
	goji.Use(context.ClearHandler)

	goji.Get("/", handler(serveIndex))
	goji.Get("/login", handler(serveLogin))
	goji.Get("/github_callback", handler(serveGitHubCallback))
	// TODO(samertm): Make this POST /user/email.
	goji.Post("/save_email", handler(serveSaveEmail))

	goji.Post("/group/create", handler(serveGroupCreate))
	goji.Post("/group/:group_id/refresh", handler(serveGroupRefresh))
	goji.Get("/group/:group_id/join", handler(serveGroupJoin))
	goji.Get("/group/:group_id", handler(serveGroup))
	goji.Get("/group/:group_id/user/:user_id/stats.svg", handler(serveUserStatsSVG))

	goji.Serve()
}
Example #6
0
func initRoutes() {

	// Setup static files
	static := web.New()
	static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))

	http.Handle("/static/", static)

	// prepare routes, get/post stuff etc
	goji.Get("/", startPage)
	goji.Post("/held/action/:action/*", runActionAndRedirect)
	goji.Post("/held/complexaction", runComplexActionAndRedirect)
	goji.Post("/held/save", saveHeld)

	goji.Get("/held/isValid", isValid)
	// partial html stuff - sub-pages
	goji.Get("/held/page/new", pageNew)
	goji.Get("/held/page/modEigenschaften", pageModEigenschaften)
	goji.Get("/held/page/selectKampftechniken", pageSelectKampftechiken)
	goji.Get("/held/page/allgemeines", pageAllgemeines)
	goji.Get("/held/page/professionsAuswahl", pageAuswahlProfession)
	goji.Get("/held/page/kampftechniken", pageKampftechniken)
	goji.Get("/held/page/talente", pageTalente)
	goji.Get("/held/page/footer", pageFooter)
	goji.Get("/held/page/karmales", pageLiturgien)
	goji.Get("/held/page/magie", pageZauber)

	// json-accessors/ partial rest-API?
	goji.Get("/held/data/ap", getAP)
}
Example #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()
}
Example #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()
}
Example #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)
	}
}
Example #10
0
func init() {
	goji.Get("/api/sold", store.SoldHandler)
	goji.Post("/api/pay", store.PaymentHandler)
	goji.Get("/api/orders", store.OrdersHandler)
	goji.Post("/api/charge", store.ChargeHandler)
	goji.Post("/api/ship", store.ShipHandler)
	goji.Get("/api/images", images.ImageListHandler)
	goji.Serve()
}
Example #11
0
func main() {
	host := os.Getenv("ISUCONP_DB_HOST")
	if host == "" {
		host = "localhost"
	}
	port := os.Getenv("ISUCONP_DB_PORT")
	if port == "" {
		port = "3306"
	}
	_, err := strconv.Atoi(port)
	if err != nil {
		log.Fatalf("Failed to read DB port number from an environment variable ISUCONP_DB_PORT.\nError: %s", err.Error())
	}
	user := os.Getenv("ISUCONP_DB_USER")
	if user == "" {
		user = "******"
	}
	password := os.Getenv("ISUCONP_DB_PASSWORD")
	dbname := os.Getenv("ISUCONP_DB_NAME")
	if dbname == "" {
		dbname = "isuconp"
	}

	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
		user,
		password,
		host,
		port,
		dbname,
	)

	db, err = sqlx.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Failed to connect to DB: %s.", err.Error())
	}
	defer db.Close()

	goji.Get("/initialize", getInitialize)
	goji.Get("/login", getLogin)
	goji.Post("/login", postLogin)
	goji.Get("/register", getRegister)
	goji.Post("/register", postRegister)
	goji.Get("/logout", getLogout)
	goji.Get("/", getIndex)
	goji.Get(regexp.MustCompile(`^/@(?P<accountName>[a-zA-Z]+)$`), getAccountName)
	goji.Get("/posts", getPosts)
	goji.Get("/posts/:id", getPostsID)
	goji.Post("/", postIndex)
	goji.Get("/image/:id.:ext", getImage)
	goji.Post("/comment", postComment)
	goji.Get("/admin/banned", getAdminBanned)
	goji.Post("/admin/banned", postAdminBanned)
	goji.Get("/*", http.FileServer(http.Dir("../public")))
	goji.Serve()
}
Example #12
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()
}
Example #13
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)
}
Example #14
0
func main() {
	filename := flag.String("config", "config.toml", "Path to configuration file")

	flag.Parse()
	defer glog.Flush()

	var application = &system.Application{}

	application.Init(filename)
	application.LoadTemplates()

	// Setup static files
	static := web.New()
	publicPath := application.Config.Get("general.public_path").(string)
	static.Get("/assets/*", http.StripPrefix("/assets/", http.FileServer(http.Dir(publicPath))))

	http.Handle("/assets/", static)

	// Apply middleware
	goji.Use(application.ApplyTemplates)
	goji.Use(application.ApplySessions)
	goji.Use(application.ApplyDbMap)
	goji.Use(application.ApplyAuth)
	goji.Use(application.ApplyIsXhr)
	goji.Use(application.ApplyCsrfProtection)
	goji.Use(context.ClearHandler)

	controller := &controllers.MainController{}

	// Couple of files - in the real world you would use nginx to serve them.
	goji.Get("/robots.txt", http.FileServer(http.Dir(publicPath)))
	goji.Get("/favicon.ico", http.FileServer(http.Dir(publicPath+"/images")))

	// Home page
	goji.Get("/", application.Route(controller, "Index"))

	// Sign In routes
	goji.Get("/signin", application.Route(controller, "SignIn"))
	goji.Post("/signin", application.Route(controller, "SignInPost"))

	// Sign Up routes
	goji.Get("/signup", application.Route(controller, "SignUp"))
	goji.Post("/signup", application.Route(controller, "SignUpPost"))

	// KTHXBYE
	goji.Get("/logout", application.Route(controller, "Logout"))

	graceful.PostHook(func() {
		application.Close()
	})
	goji.Serve()
}
Example #15
0
func main() {
	filename := flag.String("config", "config.json", "Path to configuration file")

	flag.Parse()
	defer glog.Flush()

	var application = &system.Application{}

	application.Init(filename)
	application.LoadTemplates()
	application.ConnectToDatabase()

	// Setup static files
	static := gojiweb.New()
	static.Get("/assets/*", http.StripPrefix("/assets/", http.FileServer(http.Dir(application.Configuration.PublicPath))))

	http.Handle("/assets/", static)

	// Apply middleware
	goji.Use(application.ApplyTemplates)
	goji.Use(application.ApplySessions)
	goji.Use(application.ApplyDatabase)
	goji.Use(application.ApplyAuth)

	controller := &web.Controller{}

	// Couple of files - in the real world you would use nginx to serve them.
	goji.Get("/robots.txt", http.FileServer(http.Dir(application.Configuration.PublicPath)))
	goji.Get("/favicon.ico", http.FileServer(http.Dir(application.Configuration.PublicPath+"/images")))

	// Homec page
	goji.Get("/", application.Route(controller, "Index"))

	// Sign In routes
	goji.Get("/signin", application.Route(controller, "SignIn"))
	goji.Post("/signin", application.Route(controller, "SignInPost"))

	// Sign Up routes
	goji.Get("/signup", application.Route(controller, "SignUp"))
	goji.Post("/signup", application.Route(controller, "SignUpPost"))

	// KTHXBYE
	goji.Get("/logout", application.Route(controller, "Logout"))

	graceful.PostHook(func() {
		application.Close()
	})
	goji.Serve()
}
Example #16
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)
	}
}
Example #17
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()
}
Example #18
0
func setupAndServe() {
	goji.Post("/state", post)
	goji.Get("/state/:id", get)
	goji.Get("/target", target)
	goji.Get("/inputs", inputs)
	goji.Serve()
}
Example #19
0
func main() {
	awsSession := session.New()
	awsSession.Config.WithRegion(os.Getenv("AWS_REGION"))

	tree = &dynamotree.Tree{
		TableName: "hstore-example-shortlinks",
		DB:        dynamodb.New(awsSession),
	}
	err := tree.CreateTable()
	if err != nil {
		log.Fatalf("hstore: %s", err)
	}

	goji.Get("/:link", ServeLink)
	goji.Post("/signup", CreateAccount)

	authMux := web.New()
	authMux.Use(RequireAccount)
	authMux.Post("/", CreateLink)
	authMux.Get("/", ListLinks)
	authMux.Delete("/:link", DeleteLink) // TODO(ross): this doesn't work (!)
	goji.Handle("/", authMux)

	goji.Serve()
}
Example #20
0
func main() {
	hb := web.GojiHandlerBuilder{NewContext}

	goji.Get("/user", hb.Build(GetUser{}))
	goji.Post("/user", hb.Build(UpdateUser{}))
	goji.Serve()
}
Example #21
0
File: main.go Project: 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()
}
func main() {
	createDB()
	goji.Get("/api/posts/", readPosts)
	goji.Post("/api/posts/", insertPost)
	goji.Get("/*", http.FileServer(http.Dir("./static/")))
	goji.Serve()
}
Example #23
0
func main() {
	var dumpConf bool
	var confFile string

	flag.BoolVar(&dumpConf, "dumpconf", false, "dump the default configuration file")
	flag.StringVar(&confFile, "conf", "", "use this alternative configuration file")
	flag.Parse()

	stdoutLogger = log.New(os.Stderr, "", log.Flags())

	if dumpConf {
		dumpDefaultConf()
		return
	}

	rand.Seed(time.Now().Unix())

	if confFile != "" {
		setConf(confFile)
	}

	if conf.RealIP {
		goji.Insert(middleware.RealIP, middleware.Logger)
	}

	goji.Get("/", root)
	goji.Get("/:id", getPaste)
	goji.Post("/", createPaste)
	goji.Serve()
}
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)
}
Example #25
0
func main() {
	// setup genmai
	db, err := genmai.New(&genmai.SQLite3Dialect{}, ":memory:")
	if err != nil {
		log.Fatalln(err)
	}
	if err := db.CreateTableIfNotExists(&NodeInfo{}); err != nil {
		log.Fatalln(err)
	}

	// setup pongo
	pongo2.DefaultSet.SetBaseDirectory("templates")

	fantasy := &Fantasy{
		DB: db,
	}
	pongo2.Globals["Fantasy"] = fantasy

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

	goji.Get("/", index)
	goji.Post("/create", create)
	goji.Get("/console/:id", console)
	goji.Get("/assets/*", http.FileServer(http.Dir(".")))
	goji.Serve()
}
Example #26
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)
			}
		}
	}
}
Example #27
0
// initServer initialize and start the web server.
func initServer(db *client.DbClient) {
	// Initialize the API controller
	controllers.Init(db)

	// Staticbin middleware
	goji.Use(gojistaticbin.Staticbin("static", Asset, gojistaticbin.Options{
		SkipLogging: true,
		IndexFile:   "index.html",
	}))

	// Httpauth middleware
	if options.AuthUser != "" && options.AuthPass != "" {
		goji.Use(httpauth.SimpleBasicAuth(options.AuthUser, options.AuthPass))
	}

	goji.Get("/api/info", controllers.Info)
	goji.Get("/api/table", controllers.Tables)
	goji.Get("/api/table/:name", controllers.Table)
	goji.Get("/api/table/:name/info", controllers.TableInfo)
	goji.Get("/api/table/:name/sql", controllers.TableSql)
	goji.Get("/api/table/:name/indexes", controllers.TableIndexes)
	goji.Get("/api/query", controllers.Query)
	goji.Post("/api/query", controllers.Query)

	address := fmt.Sprintf("%s:%d", options.HttpHost, options.HttpPort)
	flag.Set("bind", address)

	go goji.Serve()
}
Example #28
0
func Start(conn *CGRConnector, user, pass string) {
	connector = conn
	username = user
	password = pass
	templates = template.Must(template.ParseGlob("templates/*.tmpl"))

	rpc.Register(conn)

	goji.Get(LOGIN_PATH, loginGet)
	goji.Post(LOGIN_PATH, loginPost)

	goji.Get("/app/*", http.FileServer(http.Dir("./static")))

	auth := web.New()
	goji.Handle("/*", auth)
	auth.Use(SessionAuth)
	auth.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) {
		jsonrpc.ServeConn(ws)
	}))
	auth.Post("/import/", importPost)
	auth.Post("/exportcdrs/", exportCdrsPost)
	auth.Post("/exporttpcsv/", exportTpToCsvPost)
	auth.Get("/accounts/logout", logoutGet)
	auth.Get("/", http.RedirectHandler("/app/", 301))
}
Example #29
0
func main() {
	flag.Parse()

	// Initialize db.
	var db db.DB
	if err := db.Open(*dbFile, 0600); err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Initialize wiki.
	w, err := wiki.NewWiki(&db)
	if err != nil {
		log.Fatal(err)
	}

	if *loggerEnabled != true {
		goji.Abandon(middleware.Logger)
	}

	// Setup up the routes for the wiki
	goji.Get("/", w.Show)
	goji.Get("/:name", w.Show)
	goji.Get("/:name/", w.RedirectToShow)
	goji.Get("/:name/edit", w.Edit)
	goji.Post("/:name", w.Update)

	// Start the web server
	goji.Serve()
}
Example #30
0
File: server.go Project: 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()

}