本文整理汇总了Golang中github.com/justinas/alice.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Router
// Router setups all the API routes and middleware
func Router() *mux.Router {
common := alice.New(middleware.Authentication, middleware.ClientName, middleware.RecoverHandler)
authOnly := alice.New(middleware.Authentication, middleware.RecoverHandler)
infoSocket := handlers.MethodHandler{
"GET": authOnly.ThenFunc(info.SocketHandler),
}
subSocket := handlers.MethodHandler{
"GET": common.ThenFunc(subscribe.Handler),
}
pubHTTP := handlers.MethodHandler{
"GET": common.ThenFunc(publish.HandlerSocket),
"POST": common.ThenFunc(publish.HandlerHTTP),
}
router := mux.NewRouter()
router.Handle("/publish", pubHTTP)
router.Handle("/subscribe", subSocket)
if config.EnableInfoSocket != "" {
router.Handle("/info", infoSocket)
}
return router
}
示例2: chain
func chain(log, cors, validate bool, f func(w http.ResponseWriter, r *http.Request)) http.Handler {
chain := alice.New(timeout)
if th != nil {
chain = alice.New(th.Throttle, timeout)
}
return chain.Then(http.HandlerFunc(custom(log, cors, validate, f)))
}
示例3: loadApps
// Create the individual API (app) specs based on live configurations and assign middleware
func loadApps(APISpecs []APISpec, Muxer *http.ServeMux) {
// load the APi defs
log.Info("Loading API configurations.")
for _, spec := range APISpecs {
// Create a new handler for each API spec
remote, err := url.Parse(spec.APIDefinition.Proxy.TargetURL)
if err != nil {
log.Error("Culdn't parse target URL")
log.Error(err)
}
if spec.UseOauth2 {
addOAuthHandlers(spec, Muxer, false)
}
proxy := TykNewSingleHostReverseProxy(remote)
spec.target = remote
proxyHandler := http.HandlerFunc(ProxyHandler(proxy, spec))
tykMiddleware := TykMiddleware{spec, proxy}
if spec.APIDefinition.UseKeylessAccess {
// for KeyLessAccess we can't support rate limiting, versioning or access rules
chain := alice.New().Then(proxyHandler)
Muxer.Handle(spec.Proxy.ListenPath, chain)
} else {
// Select the keying method to use for setting session states
var keyCheck func(http.Handler) http.Handler
if spec.APIDefinition.UseOauth2 {
// Oauth2
keyCheck = CreateMiddleware(&Oauth2KeyExists{tykMiddleware}, tykMiddleware)
} else if spec.APIDefinition.UseBasicAuth {
// Basic Auth
keyCheck = CreateMiddleware(&BasicAuthKeyIsValid{tykMiddleware}, tykMiddleware)
} else if spec.EnableSignatureChecking {
// HMAC Auth
keyCheck = CreateMiddleware(&HMACMiddleware{tykMiddleware}, tykMiddleware)
} else {
// Auth key
keyCheck = CreateMiddleware(&AuthKey{tykMiddleware}, tykMiddleware)
}
// Use CreateMiddleware(&ModifiedMiddleware{tykMiddleware}, tykMiddleware) to run custom middleware
chain := alice.New(
keyCheck,
CreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),
CreateMiddleware(&VersionCheck{tykMiddleware}, tykMiddleware),
CreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware),
CreateMiddleware(&RateLimitAndQuotaCheck{tykMiddleware}, tykMiddleware)).Then(proxyHandler)
Muxer.Handle(spec.Proxy.ListenPath, chain)
}
}
}
示例4: chainMiddleware
func chainMiddleware(ctx *base.Context, wares ...*Middleware) alice.Chain {
if len(wares) > 0 {
var m []alice.Constructor
for _, v := range wares {
m = append(m, v.ToHandler(ctx))
}
return alice.New(m...)
}
return alice.New()
}
示例5: Router
// Router gets the router with routes and their corresponding handlers defined.
// It also serves static files based on the static files path specified in the app config.
func Router(a *application.App) http.Handler {
// helper function to create Handler struct
h := func(handlerFunc func(*application.App, http.ResponseWriter, *http.Request) error) http.Handler {
return &Handler{a, handlerFunc}
}
// app specific middleware
m := middleware.Middleware{a}
router := mux.NewRouter()
router.StrictSlash(true)
// topic routes
router.Handle("/", h(getTopics))
router.Handle("/topics/new", m.MustBeAdmin(h(getNewTopic))).Methods("GET")
router.Handle("/topics/new", m.MustBeAdmin(h(postNewTopic))).Methods("POST")
// user routes
router.Handle("/users/{email}", h(getUser))
router.Handle("/login", h(getLogin))
router.Handle("/oauth2callback", h(getOauth2Callback))
router.Handle("/logout", h(getLogout))
// tag routes
router.Handle("/topics/{topicName}/tags", m.SetTopic(h(getTags)))
router.Handle("/topics/{topicName}/tags/new", m.MustBeAdmin(m.SetTopic(h(getNewTag)))).Methods("GET")
router.Handle("/topics/{topicName}/tags/new", m.MustBeAdmin(m.SetTopic(h(postNewTag)))).Methods("POST")
router.Handle("/topics/{topicName}/tags/{tagName}", m.SetTopic(m.SetTag(h(getPostsByTag))))
// post routes
p := alice.New(m.SetTopic)
router.Handle("/topics/{topicName}", p.Then(h(getPosts)))
p = p.Append(m.MustLogin)
router.Handle("/topics/{topicName}/new", p.Then(h(getNewPost))).Methods("GET")
router.Handle("/topics/{topicName}/new", p.Then(m.SetTopic(h(postNewPost)))).Methods("POST")
p = p.Append(m.SetPost)
router.Handle("/topics/{topicName}/posts/{postID}", m.SetTopic(m.SetPost(h(getPost))))
router.Handle("/topics/{topicName}/posts/{postID}/vote", p.Then(h(postPostVote))).Methods("POST")
router.Handle("/topics/{topicName}/posts/{postID}/vote", p.Then(h(deletePostVote))).Methods("DELETE")
router.Handle("/topics/{topicName}/posts/{postID}/hide", p.Then(m.MustBeAdminOrPostCreator(h(postHidePost)))).Methods("POST")
router.Handle("/topics/{topicName}/posts/{postID}/hide", p.Then(m.MustBeAdminOrPostCreator(h(deleteHidePost)))).Methods("DELETE")
router.Handle("/topics/{topicName}/posts/{postID}/pin", p.Then(m.MustBeAdmin(h(postPinPost)))).Methods("POST")
router.Handle("/topics/{topicName}/posts/{postID}/pin", p.Then(m.MustBeAdmin(h(deletePinPost)))).Methods("DELETE")
// serve static files -- should be the last route
staticFileServer := http.FileServer(http.Dir(a.Config.StaticFilesPath))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", staticFileServer))
// middleware for all routes
standardChain := alice.New(m.SetTemplateData, m.SetSessionUser)
return standardChain.Then(router)
}
示例6: Routes
// Routes returns a new Goriall router.
func Routes() *mux.Router {
chainUnauth := alice.New(middlewareLogging, middlewarePanic, middlewareNoConfig)
chainAuth := alice.New(middlewareLogging, middlewarePanic, middlewareNoConfig, middlewareAuth)
chainAdmin := alice.New(middlewareLogging, middlewarePanic, middlewareNoConfig, middlewareAuth, middlewareAdmin)
router := mux.NewRouter()
router.Handle("/setup", chainUnauth.ThenFunc(viewSetup))
router.Handle("/login", chainUnauth.ThenFunc(viewLogin))
router.Handle("/logout", chainUnauth.ThenFunc(viewLogout))
router.Handle("/callback/{service:[a-zA-Z]+}/{secret:[a-zA-Z0-9]+}", chainUnauth.ThenFunc(viewCallback))
router.Handle("/", chainAuth.ThenFunc(viewListJobs)).Name("listJobs")
router.Handle("/{jid:[0-9]+}", chainAuth.ThenFunc(viewDetailJob))
router.Handle("/{jid:[0-9]+}/cancel", chainAuth.ThenFunc(viewCancelJob))
router.Handle("/{jid:[0-9]+}/rerun", chainAuth.ThenFunc(viewRerunJob))
router.Handle("/search", chainAuth.ThenFunc(viewSearchJobs))
router.Handle("/user/settings", chainAuth.ThenFunc(viewUpdateUser))
router.Handle("/user/regenerate-accesskey", chainAuth.ThenFunc(viewRegenrateAccessKey))
router.Handle("/admin/users", chainAdmin.ThenFunc(viewAdminListUsers))
router.Handle("/admin/user/create", chainAdmin.ThenFunc(viewAdminCreateUser))
router.Handle("/admin/user/{uid:[0-9]+}", chainAdmin.ThenFunc(viewAdminUpdateUser))
router.Handle("/admin/user/delete/{uid:[0-9]+}", chainAdmin.ThenFunc(viewAdminDeleteUser))
router.Handle("/admin/repositories", chainAdmin.ThenFunc(viewAdminListRepositories))
router.Handle("/admin/repository/create", chainAdmin.ThenFunc(viewAdminCreateRepository))
router.Handle("/admin/repository/{rid:[0-9]+}", chainAdmin.ThenFunc(viewAdminUpdateRepository))
router.Handle("/admin/repository/delete/{rid:[0-9]+}", chainAdmin.ThenFunc(viewAdminDeleteRepository))
router.Handle("/admin/mailserver/update", chainAdmin.ThenFunc(viewAdminUpdateMailserver))
router.Handle("/admin/config/update", chainAdmin.ThenFunc(viewAdminUpdateConfig))
router.Handle("/admin/repository/{rid:[0-9]+}/notification/create", chainAdmin.ThenFunc(viewAdminCreateNotification))
router.Handle("/admin/repository/{rid:[0-9]+}/notification/{nid:[0-9]+}", chainAdmin.ThenFunc(viewAdminUpdateNotification))
router.Handle("/admin/repository/{rid:[0-9]+}/notification/delete/{nid:[0-9]+}", chainAdmin.ThenFunc(viewAdminDeleteNotification))
router.Handle("/admin/repository/{rid:[0-9]+}/command/create", chainAdmin.ThenFunc(viewAdminCreateCommand))
router.Handle("/admin/repository/{rid:[0-9]+}/command/{cid:[0-9]+}", chainAdmin.ThenFunc(viewAdminUpdateCommand))
router.Handle("/admin/repository/{rid:[0-9]+}/command/delete/{cid:[0-9]+}", chainAdmin.ThenFunc(viewAdminDeleteCommand))
// add rice box to serve static files. Do not use the full middleware stack but
// only the logging handler. We do not want "notConfigured" to run e.x. so we
// can make the setup look nice.
box := rice.MustFindBox("static")
staticFileServer := http.StripPrefix("/static/", http.FileServer(box.HTTPBox()))
router.Handle("/static/{path:.*}", middlewareLogging(staticFileServer))
router.Handle("/websocket", middlewareAccessKey(websocket.GetHandler()))
return router
}
示例7: add
// add registers controller ctrl, using activeRoute. If middlewares are provided, utron uses
// alice package to chain middlewares.
func (r *Router) add(activeRoute *route, ctrl Controller, middlewares ...interface{}) error {
chain := alice.New() // alice on chains
if len(middlewares) > 0 {
var m []alice.Constructor
for _, v := range middlewares {
switch v.(type) {
case func(http.Handler) http.Handler:
m = append(m, v.(func(http.Handler) http.Handler))
case func(*Context) error:
// wrap func(*Context)error to a func(http.Handler)http.Handler
//
//TODO put this into a separate function?
ctxMiddleware := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := NewContext(w, req)
r.prepareContext(ctx)
err := v.(func(*Context) error)(ctx)
if err != nil {
cerr := ctx.Commit()
if cerr != nil {
logThis.Errors(req.URL.Path, " ", cerr.Error())
}
return
}
h.ServeHTTP(ctx.Response(), ctx.Request())
})
}
m = append(m, ctxMiddleware)
default:
return fmt.Errorf("unsupported middleware %v", v)
}
}
chain = alice.New(m...)
}
// register methods if any
if len(activeRoute.methods) > 0 {
r.HandleFunc(activeRoute.pattern, func(w http.ResponseWriter, req *http.Request) {
chain.ThenFunc(r.wrapController(activeRoute.fn, ctrl)).ServeHTTP(w, req)
}).Methods(activeRoute.methods...)
return nil
}
r.HandleFunc(activeRoute.pattern, func(w http.ResponseWriter, req *http.Request) {
chain.ThenFunc(r.wrapController(activeRoute.fn, ctrl)).ServeHTTP(w, req)
})
return nil
}
示例8: New
// New created a new pointer to Sufr
func New() *Sufr {
log.Println("Creating new Sufr instance")
app := &Sufr{}
database = db.New(config.DatabaseFile)
if config.Debug {
go database.Statsdumper()
}
err := database.Open()
// Panic if we can't open the database
if err != nil {
log.Panic(err)
}
// This route is used to initially configure the instance
router.Handle("/config", errorHandler(registrationHandler)).Methods("POST", "GET").Name("config")
router.Handle("/login", errorHandler(loginHandler)).Methods("POST", "GET").Name("login")
router.Handle("/logout", errorHandler(logoutHandler)).Methods("POST", "GET").Name("logout")
all := alice.New(SetSettingsHandler, SetLoggedInHandler, SetActiveTabHandler, LoggingHandler)
auth := alice.New(AuthHandler)
auth = auth.Extend(all)
router.Handle("/", all.Then(errorHandler(urlIndexHandler))).Name("url-index")
urlrouter := router.PathPrefix("/url").Subrouter()
urlrouter.Handle("/new", auth.Then(errorHandler(urlNewHandler))).Name("url-new")
urlrouter.Handle("/submit", auth.Then(errorHandler(urlSubmitHandler))).Methods("POST").Name("url-submit")
urlrouter.Handle("/{id:[0-9]+}", all.Then(errorHandler(urlViewHandler))).Name("url-view")
urlrouter.Handle("/{id:[0-9]+}/edit", auth.Then(errorHandler(urlEditHandler))).Name("url-edit")
urlrouter.Handle("/{id:[0-9]+}/save", auth.Then(errorHandler(urlSaveHandler))).Methods("POST").Name("url-save")
urlrouter.Handle("/{id:[0-9]+}/delete", auth.Then(errorHandler(urlDeleteHandler))).Name("url-delete")
urlrouter.Handle("/{id:[0-9]+}/toggle-fav", auth.Then(errorHandler(urlFavHandler))).Methods("POST").Name("url-fav-toggle")
tagrouter := router.PathPrefix("/tag").Subrouter()
tagrouter.Handle("/", all.Then(errorHandler(tagIndexHandler))).Name("tag-index")
tagrouter.Handle("/{id:[0-9]+}", all.Then(errorHandler(tagViewHandler))).Name("tag-view")
router.Handle("/import/shitbucket", auth.Then(errorHandler(shitbucketImportHandler))).Methods("POST", "GET").Name("shitbucket-import")
router.Handle("/settings", auth.Then(errorHandler(settingsHandler))).Methods("POST", "GET").Name("settings")
router.Handle("/database-backup", auth.Then(errorHandler(database.BackupHandler))).Methods("GET").Name("database-backup")
router.PathPrefix("/static").Handler(staticHandler)
router.NotFoundHandler = errorHandler(func(w http.ResponseWriter, r *http.Request) error {
w.WriteHeader(http.StatusNotFound)
return renderTemplate(w, "404", nil)
})
return app
}
示例9: routes
func routes() *httprouter.Router {
r := httprouter.New()
// Set 404 handler
r.NotFound = alice.
New().
ThenFunc(controller.Error404)
// Serve static files, no directory browsing
r.GET("/static/*filepath", hr.Handler(alice.
New().
ThenFunc(controller.Static)))
// Home page
r.GET("/", hr.Handler(alice.
New().
ThenFunc(controller.Index)))
// Login
r.GET("/login", hr.Handler(alice.
New(acl.DisallowAuth).
ThenFunc(controller.LoginGET)))
r.POST("/login", hr.Handler(alice.
New(acl.DisallowAuth).
ThenFunc(controller.LoginPOST)))
r.GET("/logout", hr.Handler(alice.
New().
ThenFunc(controller.Logout)))
// Register
r.GET("/register", hr.Handler(alice.
New(acl.DisallowAuth).
ThenFunc(controller.RegisterGET)))
r.POST("/register", hr.Handler(alice.
New(acl.DisallowAuth).
ThenFunc(controller.RegisterPOST)))
// About
r.GET("/about", hr.Handler(alice.
New().
ThenFunc(controller.AboutGET)))
// Enable Pprof
r.GET("/debug/pprof/*pprof", hr.Handler(alice.
New(acl.DisallowAnon).
ThenFunc(pprofhandler.Handler)))
return r
}
示例10: main
func main() {
//initialize the stock account
var st = (new(StockAccounts))
//initialize a tradeId with random number
tradeId = rand.Intn(10000) + 1
// //register the stock account data and start server with HTTP protocol
// rpc.Register(&st)
// rpc.HandleHTTP()
// //start listening
// err := http.ListenAndServe(":1234", nil) //nil, no need for handler
router := mux.NewRouter()
server := rpc.NewServer()
server.RegisterCodec(json.NewCodec(), "application/json")
server.RegisterService(st, "")
chain := alice.New(
func(h http.Handler) http.Handler {
return handlers.CombinedLoggingHandler(os.Stdout, h)
},
handlers.CompressHandler,
func(h http.Handler) http.Handler {
return recovery.Handler(os.Stderr, h, true)
})
router.Handle("/rpc", chain.Then(server))
log.Fatal(http.ListenAndServe(":1234", server))
// checkError(err)
}
示例11: StartServer
func (h WebserviceHandler) StartServer() {
commonHandlers := alice.New(context.ClearHandler, h.LoggingHandler, h.RecoverHandler, h.NoCacheHandler)
authHandlers := commonHandlers.Append(h.AuthHandler)
h.mrouter = NewRouter()
h.frouter = http.NewServeMux()
h.frouter.Handle("/", http.FileServer(http.Dir(h.config.GetHTTPDir())))
h.mrouter.Get("/item.html", authHandlers.ThenFunc(h.ItemHTML))
h.mrouter.Get("/services/items", commonHandlers.ThenFunc(h.GetItems))
h.mrouter.Get("/services/bestComments", commonHandlers.Append(h.GzipJsonHandler).ThenFunc(h.GetBestComments))
h.mrouter.Post("/services/register", commonHandlers.ThenFunc(h.Register))
h.mrouter.Post("/services/login", commonHandlers.ThenFunc(h.Login))
h.mrouter.Get("/services/confirm", commonHandlers.ThenFunc(h.ConfirmEmail))
h.mrouter.Get("/services/itemInfo", commonHandlers.Append(h.GzipJsonHandler).ThenFunc(h.GetItemInfo))
h.mrouter.Get("/services/logout", authHandlers.ThenFunc(h.Logout))
h.mrouter.Get("/services/like", authHandlers.ThenFunc(h.PostLike))
h.mrouter.Post("/services/comment", authHandlers.ThenFunc(h.PostComment))
h.mrouter.Get("/services/deletecomment", authHandlers.ThenFunc(h.DeleteComment))
h.mrouter.Post("/services/deployFront", commonHandlers.Append(h.BasicAuth).ThenFunc(h.DeployFront))
var err error
r := http.NewServeMux()
r.HandleFunc("/", h.FrontHandler)
go func() {
log.Infof("Server launched on port %s", h.config.GetServerPort())
err = http.ListenAndServe(":"+h.config.GetServerPort(), r)
if err != nil {
panic(err.Error())
}
}()
}
示例12: Stack
func Stack() *App {
app := App{R: httprouter.New()}
app.Stack = alice.New(app.logger, app.recovery)
app.Context = make(map[string]interface{})
return &app
}
示例13: main
func main() {
settings.Setup()
err := settings.Build()
if err != nil {
log.Fatal(fmt.Errorf("Unable to load configuration, %v", err))
}
runtime.GOMAXPROCS(settings.Config.NumCPU)
printBanner(settings.Config)
fs := http.FileServer(http.Dir("./static"))
router := mux.NewRouter()
commonHandlers := alice.New(loggingHandler, recoverHandler)
// Mandatory root-based resources
serveSingle(router, "/favicon.ico", "./static/favicon.ico")
serveSingle(router, "/robots.txt", "./static/robots.txt")
router.PathPrefix("/static/").Handler(viewer.ServeStatic(http.StripPrefix("/static/", fs))).Methods("GET")
router.NotFoundHandler = http.HandlerFunc(viewer.NotFoundPage())
server := deliver.New(settings.Config.Workers)
router.Handle("/{filename:.+}", server).Methods("GET")
log.Fatal(http.ListenAndServe(settings.Config.Address+":"+settings.Config.Port, commonHandlers.Then(router)))
}
示例14: main
func main() {
if flgVersion {
fmt.Println(VERSION)
return
}
r := http.NewServeMux()
loggingHandler := func(h http.Handler) http.Handler {
return gh.LoggingHandler(os.Stdout, h)
}
commonHandlers := alice.New(handlers.RecoverHandler, gh.ProxyHeaders, loggingHandler)
r.Handle("/", commonHandlers.ThenFunc(RootHandler))
r.Handle("/robots.txt", commonHandlers.ThenFunc(RobotsTxtHandler))
r.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(flgStaticPath))))
addr := fmt.Sprintf("%s:%d", flgHost, flgPort)
log.Printf("Listening on %s", addr)
err := http.ListenAndServe(addr, r)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}
示例15: main
func main() {
var err error
endpoint := ":3000"
wiki, err = newFileDB("wiki_db")
//wiki, err = newMemDB()
if err != nil {
panic(err.Error())
}
stdMw := alice.New(middleware.MustGet("middleware.LoggingStdOut"), middleware.MustGet("middleware.Panic"))
r := mux.NewRouter()
r.Handle("/", stdMw.Then(adapt(wiki, ListPagesHandler))).Methods("GET")
r.Handle("/About/", stdMw.Then(adapt(wiki, AboutPageHandler))).Methods("GET")
r.Handle("/static/{path:.*}", http.FileServer(http.Dir("public/")))
r.Handle("/edit/{name}/", stdMw.Then(adapt(wiki, ShowEditPageHandler))).Methods("GET")
r.Handle("/edit/{name}/", stdMw.Then(adapt(wiki, EditPageHandler))).Methods("POST")
r.Handle("/edit/:name/attachment/", stdMw.Then(adapt(wiki, AddAttachmentHandler))).Methods("POST")
r.Handle("/{name}/", stdMw.Then(adapt(wiki, PageHandler))).Methods("GET")
r.Handle("/{name}/{attachment}", stdMw.Then(adapt(wiki, AttachmentHandler))).Methods("GET")
os.Stdout.WriteString("Staring wiki at " + endpoint + "\n")
http.ListenAndServe(endpoint, r)
}