コード例 #1
0
ファイル: app.go プロジェクト: BIT66COM/gateway-server
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()
}
コード例 #2
0
ファイル: main.go プロジェクト: changwng/sqliteweb
// 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()
}
コード例 #3
0
ファイル: main.go プロジェクト: 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()
}
コード例 #4
0
ファイル: main.go プロジェクト: mikerjacobi/goji-skeleton
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()
}
コード例 #5
0
ファイル: main.go プロジェクト: samertm/githubstreaks
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()
}
コード例 #6
0
ファイル: main.go プロジェクト: ignaciocarvajal/go-portafolio
func main() {

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

	goji.Get("/", handlers.GetHome)
	goji.Serve()
}
コード例 #7
0
ファイル: main.go プロジェクト: jjenkins/heartkit
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()
}
コード例 #8
0
ファイル: main.go プロジェクト: sheercat/anyweb
func main() {

	pongo2.DefaultLoader.SetBaseDir("view")

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

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

	goji.Serve()
}
コード例 #9
0
ファイル: main.go プロジェクト: kyokomi-sandbox/sandbox
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()
}
コード例 #10
0
ファイル: mcs-stats.go プロジェクト: guijun/mcs-stats
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()
}
コード例 #11
0
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

}
コード例 #12
0
ファイル: server.go プロジェクト: maxkoi/d7024e_website
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()
}
コード例 #13
0
ファイル: app.go プロジェクト: plirr/goji-wiki
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()
}
コード例 #14
0
ファイル: csp_test.go プロジェクト: herveleclerc/linx-server
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)
		}
	}
}
コード例 #15
0
ファイル: fantasy.go プロジェクト: fgken/fantasy
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()
}
コード例 #16
0
ファイル: server.go プロジェクト: ksimka/goapi-demo
func main() {
	goji.Use(ContentTypeJson)
	goji.Get("/jokes/:jokeId", showJoke)
	goji.Serve()

	db.Close()
}
コード例 #17
0
ファイル: run_http.go プロジェクト: jmptrader/ogo
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()
}
コード例 #18
0
ファイル: webserver.go プロジェクト: topscore/sup
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
}
コード例 #19
0
ファイル: main.go プロジェクト: samertm/sample-goji-app
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()
}
コード例 #20
0
ファイル: main.go プロジェクト: changwng/sqliteweb
func main() {
	goji.Use(gojistaticbin.Staticbin("static", Asset, gojistaticbin.Options{
		SkipLogging: false,
		IndexFile:   "index.html",
	}))

	goji.Serve()
}
コード例 #21
0
ファイル: main.go プロジェクト: felixalias/negotiator
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()
}
コード例 #22
0
ファイル: goji.go プロジェクト: jeevatkm/middleware
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()
}
コード例 #23
0
ファイル: main.go プロジェクト: nbgo/extdirect
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()
}
コード例 #24
0
ファイル: lastweek.go プロジェクト: topscore/lastweek
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()
}
コード例 #25
0
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()
}
コード例 #26
0
ファイル: main.go プロジェクト: jchannon/FarGo
func main() {
	goji.Use(middleware.EnvInit)
	tweetmodule.New()

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

	goji.Serve()

}
コード例 #27
0
ファイル: main.go プロジェクト: grounded042/capacious
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()
}
コード例 #28
0
ファイル: server.go プロジェクト: yudppp/godzilla
func main() {
	// Serve static files
	goji.Use(Static("public"))

	// Add routes
	routes.Include()

	// Run Goji
	goji.Serve()
}
コード例 #29
0
ファイル: main.go プロジェクト: a-r-g-v/mitei
func main() {

	punch.Setup()

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

}
コード例 #30
0
ファイル: main.go プロジェクト: born-in-makuhari/kanban
func main() {
	// setup static
	goji.Use(gojistatic.Static("public",
		gojistatic.StaticOptions{SkipLogging: true}))

	// app routing
	Route(goji.DefaultMux)

	// start server
	goji.Serve()
}