本文整理汇总了Golang中github.com/zenazn/goji.Use函数的典型用法代码示例。如果您正苦于以下问题:Golang Use函数的具体用法?Golang Use怎么用?Golang Use使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Use函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Serve
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: initServer
// 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: main
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: main
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: main
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: main
func main() {
goji.Use(static.Static("static"))
goji.Use(render.InjectRender)
goji.Get("/", handlers.GetHome)
goji.Serve()
}
示例7: main
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: main
func main() {
pongo2.DefaultLoader.SetBaseDir("view")
goji.Use(middleware.Recoverer)
goji.Use(middleware.NoCache)
goji.Get("/", inquiry)
goji.Post("/", sendInquiry)
goji.Serve()
}
示例9: main
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: main
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: init
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: main
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: main
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: TestContentSecurityPolicy
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: main
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()
}