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()
}
Exemplo n.º 2
0
func main() {
	defer glog.Flush()
	glog.Info("Initializing shellscript executor server")

	port := flag.String("P", "6304", "port")
	flag.Parse()

	flag.Lookup("logtostderr").Value.Set("true")

	EnvSettingsInit()
	//read dictionary into memory
	dicData, err := ioutil.ReadFile(ProjectEnvSettings.DictionaryPath)
	if err != nil {
		FailOnError(err, fmt.Sprintf("Error[%s] reading dictionary from path[%]", err, ProjectEnvSettings.DictionaryPath))
	}

	glog.Infof("Dictionary[%s]", dicData)

	if err := json.Unmarshal(dicData, &dictionary); err != nil {
		FailOnError(err, fmt.Sprintf("Error[%s] decode json dictionary from path[%] with content[%s]", err, ProjectEnvSettings.DictionaryPath, dicData))
	}

	goji.Get("/shell/execute/:action_name", executeShellScriptHandler)

	flag.Set("bind", ":"+*port)
	goji.Serve()
}
Exemplo n.º 3
0
func main() {
	filename := flag.String("config", "config.toml", "Path to configuration file")
	flag.Parse()
	fmt.Println(*filename)
	goji.Get("/hello/:name", hello)
	goji.Serve()
}
Exemplo n.º 4
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()
}
Exemplo n.º 5
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	log.SetOutput(ioutil.Discard) // add line 3
	db, err := sql.Open("mysql", connectionString)
	if err != nil {
		log.Fatalf("Error opening database: %v", err)
	}
	db.SetMaxIdleConns(maxConnectionCount)
	worldStatement, err = db.Prepare(worldSelect)
	if err != nil {
		log.Fatal(err)
	}
	fortuneStatement, err = db.Prepare(fortuneSelect)
	if err != nil {
		log.Fatal(err)
	}
	updateStatement, err = db.Prepare(worldUpdate)
	if err != nil {
		log.Fatal(err)
	}

	flag.Set("bind", ":8080")
	goji.Get("/json", serializeJson)
	goji.Get("/db", singleQuery)
	goji.Get("/queries", multipleQueries)
	goji.Get("/fortunes", fortunes)
	goji.Get("/plaintext", plaintext)
	goji.Get("/updates", dbupdate)
	goji.Serve()
}
Exemplo n.º 6
0
func main() {
	render := render.New(render.Options{
		Directory:  "src/views",
		Extensions: []string{".html"},
	})

	http.HandleFunc("/img/", serveResource)
	http.HandleFunc("/css/", serveResource)
	http.HandleFunc("/js/", serveResource)

	goji.Get("/hello/:name", func(c web.C, w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"])
	})

	goji.Get("/wow", func(c web.C, w http.ResponseWriter, r *http.Request) {
		render.HTML(w, http.StatusOK, "index", nil)
	})

	goji.Get("/bar", func(c web.C, w http.ResponseWriter, r *http.Request) {
		render.HTML(w, http.StatusOK, "bar", nil)
	})

	goji.Get("/", func(c web.C, w http.ResponseWriter, r *http.Request) {
		render.HTML(w, http.StatusOK, "index", nil)
	})

	goji.Serve()
}
Exemplo n.º 7
0
func WebServer(ip string, port int) {

	goji.Get("/", func(c web.C, w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page!")
	})

	goji.Get("/search", func(c web.C, w http.ResponseWriter, r *http.Request) {
		filter := db.Filter{}
		options := &db.Options{}

		r.ParseForm()
		startDate := r.Form.Get("startDate")
		endDate := r.Form.Get("endDate")

		if startDate != "" {
			filter.StartDate = startDate
		}

		if endDate != "" {
			filter.EndDate = endDate
		}

		order := r.Form["orderby"]
		options.Sort = order

		var results []db.DbObject

		db.Db.Find(&filter, options, &results)
		jsonResults, err := json.Marshal(results)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		fmt.Fprintf(w, "%s", string(jsonResults))
	})

	goji.Get("/call/:id", func(c web.C, w http.ResponseWriter, r *http.Request) {
		callId := c.URLParams["id"]
		fmt.Print(callId)
		filter := db.NewFilter()
		options := &db.Options{}

		filter.Equals["callid"] = callId

		var results []db.DbObject
		db.Db.Find(&filter, options, &results)

		jsonResults, err := json.Marshal(results)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		fmt.Fprintf(w, "%s", string(jsonResults))

	})

	goji.Serve()
}
Exemplo n.º 8
0
func main() {
	goji.Get("/", IndexHandler) // Doesn't need CSRF protection (no POST/PUT/DELETE actions).

	signup := web.New()
	goji.Handle("/signup/*", signup)
	// But our signup forms do, so we add nosurf to their middleware stack (only).
	signup.Use(nosurf.NewPure)
	signup.Get("/signup/new", ShowSignupForm)
	signup.Post("/signup/submit", SubmitSignupForm)

	admin := web.New()
	// A more advanced example: we enforce secure cookies (HTTPS only),
	// set a domain and keep the expiry time low.
	a := nosurf.New(admin)
	a.SetBaseCookie(http.Cookie{
		Name:     "csrf_token",
		Domain:   "localhost",
		Path:     "/admin",
		MaxAge:   3600 * 4,
		HttpOnly: true,
		Secure:   true,
	})

	// Our /admin/* routes now have CSRF protection.
	goji.Handle("/admin/*", a)

	goji.Serve()
}
Exemplo n.º 9
0
func main() {
	goji.Use(ContentTypeJson)
	goji.Get("/jokes/:jokeId", showJoke)
	goji.Serve()

	db.Close()
}
Exemplo n.º 10
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()
}
Exemplo n.º 11
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()
}
Exemplo n.º 12
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()
}
Exemplo n.º 13
0
func main() {
	rand.Seed(time.Now().UnixNano())
	goji.Get("/slow", slow)
	goji.Get("/bad", bad)
	goji.Get("/timeout", timeout)
	goji.Serve()
}
Exemplo n.º 14
0
func main() {
	goji.Get("/hello/:name", hello)

	staticPattern := regexp.MustCompile("^/(css|js)")
	goji.Handle(staticPattern, http.FileServer(http.Dir("./static")))
	goji.Serve()
}
Exemplo n.º 15
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()
}
Exemplo n.º 16
0
func main() {
	kiiApp := models.KiiApp{AppID: "1ef175ad", AppKey: "2a0ed4f8a93d83d9ff3991f75087602d"}

	userCtl := controllers.NewUserController(kiiApp)
	eventCtl := controllers.NewEventController(kiiApp)
	likeCtl := controllers.NewLikeController(kiiApp)

	// Create User
	goji.Post(VERSION+"/user/create", userCtl.CreateUser)
	// Login User
	goji.Post(VERSION+"/user/login", userCtl.LoginUser)
	// Get Login User Info
	goji.Get(VERSION+"/user/me", userCtl.Me)

	// Create Event
	goji.Post(VERSION+"/event", eventCtl.CreateEvent)
	// Delete Event
	goji.Post(VERSION+"/event/delete", eventCtl.DeleteEvent)
	// Get Event
	goji.Get(VERSION+"/events", eventCtl.GetEvents)
	// Add Visit Number
	goji.Post(VERSION+"/event/visit", eventCtl.Visit)

	// Add Like
	goji.Post(VERSION+"/like", likeCtl.AddLike)

	goji.Serve()
}
Exemplo n.º 17
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()
}
Exemplo n.º 18
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()
}
Exemplo n.º 19
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()
}
Exemplo n.º 20
0
func main() {
	flag.Parse()
	admin.Start(admin.NewCGRConnector("json", *server, *redisCon), *username, *password)

	flag.Set("bind", ":8080")
	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()
}
Exemplo n.º 22
0
func main() {
	ws := realtime.NewServer("/ws")
	go ws.Listen()

	controllers.Asset = Asset

	config := models.LoadConfig(os.Getenv("HOME") + "/.mouryou.json")
	controllers.Cluster = &config.Cluster

	top := &controllers.TopController{}
	cluster := &controllers.ClusterController{}
	cluster.LoadBalancer = &controllers.LoadBalancerController{}
	cluster.Hypervisors = &controllers.HypervisorsController{}
	cluster.Hypervisors.VirtualMachines = &controllers.VirtualMachinesController{}

	goji.Get("/assets/*", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "/"}))
	goji.Get("/frontend/*", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "/"}))
	goji.Get("/api/cluster", cluster.IndexAPI)
	goji.Get("/api/cluster/load_balancer", cluster.LoadBalancer.IndexAPI)
	goji.Get("/api/cluster/hypervisors", cluster.Hypervisors.IndexAPI)
	goji.Get("/api/cluster/hypervisors/:hid", cluster.Hypervisors.ShowAPI)
	goji.Get("/api/cluster/hypervisors/:hid/virtual_machines", cluster.Hypervisors.VirtualMachines.IndexAPI)
	goji.Get("/api/cluster/hypervisors/:hid/virtual_machines/:vid", cluster.Hypervisors.VirtualMachines.ShowAPI)
	goji.Get("/", top.Index)

	goji.Serve()
}
func main() {
	createDB()
	goji.Get("/api/posts/", readPosts)
	goji.Post("/api/posts/", insertPost)
	goji.Get("/*", http.FileServer(http.Dir("./static/")))
	goji.Serve()
}
Exemplo n.º 24
0
func main() {

	goji.Get("/", home)
	goji.Get("/script/ajax.php", ajax)
	goji.Get("/assets/*", http.FileServer(FS(false)))
	goji.Serve()
}
Exemplo n.º 25
0
func main() {

	//setup sessions
	/*
		sh := redis.NewSessionHolder()
		redisconfig := viper.GetStringMapString("redis")
		if _, ok := redisconfig["host"]; !ok {
			panic("failed to read redis host")
		}
		if _, ok := redisconfig["port"]; !ok {
			panic("failed to read redis port")
		}

		redisip, err := alias2ipaddr(redisconfig["host"])
		if err != nil {
			panic("failed to lookup redis IP address")
		}
		goji.Use(redis.BuildRedis(fmt.Sprintf("%s:%s", redisip, redisconfig["port"])))
		goji.Use(base.BuildSessionMiddleware(sh))
	*/

	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})
	goji.Use(c.Handler)

	//setup render middleware
	goji.Use(middleware.RenderMiddleware)

	//setup database
	/*
		dbconfig := viper.GetStringMapString("db")
		if _, ok := dbconfig["host"]; !ok {
			panic("failed to read db host")
		}
		if _, ok := dbconfig["name"]; !ok {
			panic("failed to read db name")
		}
		goji.Use(middleware.PostgresMiddleware)

		goji.Use(middleware.AuthMiddleware)
	*/

	//setup routes
	goji.Get("/home", controllers.IndexHandler)
	goji.Get("/healthcheck", controllers.HealthCheckHandler)
	goji.Get("/login", controllers.Login)
	goji.Get("/oauth2callback", controllers.OAuth2Callback)
	//goji.Get("/logout", controllers.Logout)

	//setup static assets
	goji.Use(gojistatic.Static("/go/src/bower_components", gojistatic.StaticOptions{SkipLogging: true, Prefix: "bower_components"}))
	goji.Use(gojistatic.Static("/go/src/frontend/js", gojistatic.StaticOptions{SkipLogging: true, Prefix: "js"}))

	//begin
	log.Info("Starting App...")

	flag.Set("bind", ":80")
	goji.Serve()
}
Exemplo n.º 26
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()
}
Exemplo n.º 27
0
func main() {
	hb := web.GojiHandlerBuilder{NewContext}

	goji.Get("/user", hb.Build(GetUser{}))
	goji.Post("/user", hb.Build(UpdateUser{}))
	goji.Serve()
}
Exemplo n.º 28
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()
}
Exemplo n.º 29
0
func setupAndServe() {
	goji.Post("/state", post)
	goji.Get("/state/:id", get)
	goji.Get("/target", target)
	goji.Get("/inputs", inputs)
	goji.Serve()
}
Exemplo n.º 30
0
Arquivo: main.go Projeto: 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()
}