Ejemplo n.º 1
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()
}
Ejemplo n.º 2
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()
}
Ejemplo n.º 3
0
Archivo: main.go Proyecto: 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()
}
Ejemplo n.º 4
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()
}
Ejemplo n.º 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()
}
Ejemplo n.º 6
0
func main() {

	goji.Use(static.Static("static"))
	goji.Use(render.InjectRender)

	goji.Get("/", handlers.GetHome)
	goji.Serve()
}
Ejemplo n.º 7
0
func main() {
	goji.Use(config)
	goji.Use(database)
	goji.Get("/", handlers.Root)
	goji.Get("/authorize", handlers.Authorize)
	goji.Get("/connected", handlers.Connected)
	goji.Get("/callback", handlers.Callback)
	goji.Post("/subscriber", handlers.Subscriber)
	goji.NotFound(handlers.NotFound)
	goji.Serve()
}
Ejemplo n.º 8
0
func main() {

	pongo2.DefaultLoader.SetBaseDir("view")

	goji.Use(middleware.Recoverer)
	goji.Use(middleware.NoCache)

	goji.Get("/", inquiry)
	goji.Post("/", sendInquiry)

	goji.Serve()
}
Ejemplo n.º 9
0
func main() {

	c := context.NewContext("goji sample")

	f := foo.NewService(c)

	goji.Use(Check1)
	goji.Use(Check2)
	goji.Get("/hello/:name", hello)
	goji.Get("/v2/hello/:name", f.HelloHandler)
	goji.Serve()
}
Ejemplo n.º 10
0
func main() {
	// Default Middleware
	goji.Use(middleware.EnvInit)
	goji.Use(middleware.Recoverer)

	goji.Post("/api/pings", HandlePing)

	// Static Files
	goji.Get("/*", http.StripPrefix("/", http.FileServer(http.Dir(config.StaticLocation))))

	// Serve using the magic of Goji!
	goji.Serve()
}
func init() {
	logr = logrus.New()
	//	logr.Formatter = new(logrus.JSONFormatter)

	appName = "OHACK_API"

	goji.Abandon(gmiddleware.Logger)             //Remove default logger
	goji.Abandon(gmiddleware.Recoverer)          //Remove default Recoverer
	goji.Use(middleware.RequestIDHeader)         //Add RequestIDHeader Middleware
	glogrus := glogrus.NewGlogrus(logr, appName) //Add custom logger Middleware
	goji.Use(glogrus)
	goji.Use(middleware.NewRecoverer(logr)) //Add custom recoverer

}
Ejemplo n.º 12
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")))

	// 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()
}
Ejemplo n.º 13
0
func main() {
	// setup tables
	db, err := genmai.New(&genmai.SQLite3Dialect{}, "./wiki.db")
	if err != nil {
		log.Fatalln(err)
	}
	if err := db.CreateTableIfNotExists(&Page{}); err != nil {
		log.Fatalln(err)
	}

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

	wiki := &Wiki{
		URL: "/",
		DB:  db,
	}
	pongo2.Globals["wiki"] = wiki
	pongo2.RegisterFilter("to_localdate", func(in *pongo2.Value, param *pongo2.Value) (out *pongo2.Value, err *pongo2.Error) {
		date, ok := in.Interface().(time.Time)
		if !ok {
			return nil, &pongo2.Error{
				Sender:   "to_localdate",
				ErrorMsg: fmt.Sprintf("Date must be of type time.Time not %T ('%v')", in, in),
			}
		}
		return pongo2.AsValue(date.Local()), nil
	})

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

	})

	goji.Get("/assets/*", http.FileServer(http.Dir(".")))
	goji.Get("/", showPages)
	goji.Get("/wiki/:title", showPage)
	goji.Get("/wiki/:title/edit", editPage)
	goji.Post("/wiki/:title", postPage)

	goji.Serve()
}
Ejemplo n.º 14
0
func TestContentSecurityPolicy(t *testing.T) {
	Config.siteURL = "http://linx.example.org/"
	Config.filesDir = path.Join(os.TempDir(), generateBarename())
	Config.metaDir = Config.filesDir + "_meta"
	Config.maxSize = 1024 * 1024 * 1024
	Config.noLogs = true
	Config.siteName = "linx"
	Config.contentSecurityPolicy = "default-src 'none'; style-src 'self';"
	Config.xFrameOptions = "SAMEORIGIN"
	mux := setup()

	w := httptest.NewRecorder()

	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	goji.Use(ContentSecurityPolicy(CSPOptions{
		policy: testCSPHeaders["Content-Security-Policy"],
		frame:  testCSPHeaders["X-Frame-Options"],
	}))

	mux.ServeHTTP(w, req)

	for k, v := range testCSPHeaders {
		if w.HeaderMap[k][0] != v {
			t.Fatalf("%s header did not match expected value set by middleware", k)
		}
	}
}
Ejemplo n.º 15
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()
}
Ejemplo n.º 16
0
func main() {
	goji.Use(ContentTypeJson)
	goji.Get("/jokes/:jokeId", showJoke)
	goji.Serve()

	db.Close()
}
Ejemplo n.º 17
0
func init() {
	// 废除全部goji默认的gojimiddle
	goji.Abandon(gojimiddle.RequestID)
	goji.Abandon(gojimiddle.Logger)
	goji.Abandon(gojimiddle.Recoverer)
	goji.Abandon(gojimiddle.AutomaticOptions)

	//增加自定义的middleware
	goji.Use(EnvInit)
	goji.Use(Defer)
	goji.Use(Mime)
	goji.Use(ParseParams)

	//mime
	initMime()
}
Ejemplo n.º 18
0
func StartWebServer(bind, auth string) error {
	err := loadTemplates()
	if err != nil {
		return err
	}

	if auth != "" {
		authParts := strings.Split(auth, ":")
		goji.Use(httpauth.SimpleBasicAuth(authParts[0], authParts[1]))
	}

	goji.Get("/", homeRoute)
	goji.Get("/status", statusRoute)
	goji.Get("/robots.txt", robotsRoute)
	goji.Get("/setEnabled", setEnabledRoute)
	goji.Handle("/config", configRoute)

	listener, err := net.Listen("tcp", bind)
	if err != nil {
		return err
	}

	goji.ServeListener(listener)
	return nil
}
Ejemplo n.º 19
0
func main() {
	// Serve static files.
	staticDirs := []string{"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("/auth_callback", handler(serveAuthCallback))
	goji.Serve()
}
Ejemplo n.º 20
0
func main() {
	goji.Use(gojistaticbin.Staticbin("static", Asset, gojistaticbin.Options{
		SkipLogging: false,
		IndexFile:   "index.html",
	}))

	goji.Serve()
}
Ejemplo n.º 21
0
func main() {
	goji.Use(negotiatormw)
	goji.Get("/", appHandler(homeHandler))
	goji.Get("/oneoffnegotiator", appHandler(customHandler))
	goji.Get("/multinegotiator", appHandler(multiNegotiatorHandler))
	goji.Get("/multinegotiatoragain", appHandler(multiNegotiatorHandlerAgain))
	goji.Serve()
}
Ejemplo n.º 22
0
func main() {

	// Adding Minify middleware
	// Note: If you use any Gzip middleware, add Minify middleware after that
	goji.Use(middleware.Minify)

	goji.Get("/", gojiHome)
	goji.Serve()
}
Ejemplo n.º 23
0
func main() {
	extdirect.Provider.RegisterAction(reflect.TypeOf(Db{}))
	goji.Get(extdirect.Provider.URL, extdirect.API(extdirect.Provider))
	goji.Post(extdirect.Provider.URL, func(c web.C, w http.ResponseWriter, r *http.Request) {
		extdirect.ActionsHandlerCtx(extdirect.Provider)(gcontext.FromC(c), w, r)
	})
	goji.Use(gojistatic.Static("public", gojistatic.StaticOptions{SkipLogging: true}))
	goji.Serve()
}
Ejemplo n.º 24
0
func main() {

	_ = goproxy.CA_CERT // so goproxy can be included and go-gettable. its not if you don't include it explicitly

	env := &Env{
		GithubClientId:     os.Getenv("GITHUB_CLIENT_ID"),
		GithubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
	}

	goji.Use(SessionMiddleware(env))

	goji.Get("/git_auth_hook", Handler{env, gitAuthRoute})
	goji.Get("/commits", Handler{env, commitsRoute})
	goji.Get("/diffstat", Handler{env, diffstatRoute})

	goji.Use(StaticMiddleware(env, "static"))

	goji.Serve()
}
func init() {
	logr = logrus.New()
	//	logr.Formatter = new(logrus.JSONFormatter)

	appName = "bloodcare.dash"

	cookieHandler = securecookie.New(
		securecookie.GenerateRandomKey(64),
		securecookie.GenerateRandomKey(32))

	goji.Abandon(gmiddleware.Logger)             //Remove default logger
	goji.Abandon(gmiddleware.Recoverer)          //Remove default Recoverer
	goji.Use(middleware.RequestIDHeader)         //Add RequestIDHeader Middleware
	glogrus := glogrus.NewGlogrus(logr, appName) //Add custom logger Middleware
	goji.Use(glogrus)
	goji.Use(middleware.NewRecoverer(logr)) //Add custom recoverer

	initTpl()
}
Ejemplo n.º 26
0
func main() {
	goji.Use(middleware.EnvInit)
	tweetmodule.New()

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

	goji.Serve()

}
Ejemplo n.º 27
0
func main() {
	var prefix = flag.String("prefix", "/api/v1", "The prefix for all calls.")

	flag.Parse()

	capaciousAPIServer := goji.DefaultMux
	ac := getAppContext()

	// apply the middleware
	goji.Use(middleware.ContentTypeHeader)
	goji.Use(middleware.JWTMiddleware)
	goji.Use(middleware.CORS)

	routes.BuildRoutes(capaciousAPIServer, routes.EventRoutes(ac.Controllers), *prefix)
	routes.BuildRoutes(capaciousAPIServer, routes.InviteeRoutes(ac.Controllers), *prefix)
	routes.BuildRoutes(capaciousAPIServer, routes.AuthRoutes(ac.Controllers), *prefix)

	goji.Serve()
}
Ejemplo n.º 28
0
func main() {
	// Serve static files
	goji.Use(Static("public"))

	// Add routes
	routes.Include()

	// Run Goji
	goji.Serve()
}
Ejemplo n.º 29
0
func main() {

	punch.Setup()

	goji.Use(httpauth.SimpleBasicAuth("a", "a"))
	goji.Post("/create", CreateController)
	goji.Get("/remove/:id", RemoveController)
	goji.Get("/", IndexController)
	goji.Serve()

}
Ejemplo n.º 30
0
func main() {
	// setup static
	goji.Use(gojistatic.Static("public",
		gojistatic.StaticOptions{SkipLogging: true}))

	// app routing
	Route(goji.DefaultMux)

	// start server
	goji.Serve()
}