本文整理匯總了Golang中github.com/codegangsta/negroni.Wrap函數的典型用法代碼示例。如果您正苦於以下問題:Golang Wrap函數的具體用法?Golang Wrap怎麽用?Golang Wrap使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Wrap函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: newNegroniMiddleware
func newNegroniMiddleware(ctx *RouterContext, middleWareFuncs []http.HandlerFunc, controllerMethod ControllerMethod) *negroni.Negroni {
negroniHandlers := []negroni.Handler{}
for ind, _ := range middleWareFuncs {
negroniHandlers = append(negroniHandlers, negroni.Wrap(middleWareFuncs[ind]))
}
negroniHandlers = append(negroniHandlers, negroni.Wrap(createHttpHandlerFunc(ctx, controllerMethod)))
return negroni.New(negroniHandlers...)
}
示例2: newNegroniMiddleware
func newNegroniMiddleware(middleWareFuncs []http.HandlerFunc, controllerMethod http.HandlerFunc) *negroni.Negroni {
negroniHandlers := []negroni.Handler{}
for ind, _ := range middleWareFuncs {
negroniHandlers = append(negroniHandlers, negroni.Wrap(middleWareFuncs[ind]))
}
negroniHandlers = append(negroniHandlers, negroni.Wrap(http.HandlerFunc(controllerMethod)))
return negroni.New(negroniHandlers...)
}
示例3: Init
func Init(apps map[string]interface{}, router *mux.Router) {
Applications = apps
// /echo/* Endpoints
echoRouter := mux.NewRouter()
// /* Endpoints
pageRouter := mux.NewRouter()
for uri, meta := range Applications {
switch app := meta.(type) {
case EchoApplication:
handlerFunc := func(w http.ResponseWriter, r *http.Request) {
echoReq := r.Context().Value("echoRequest").(*EchoRequest)
echoResp := NewEchoResponse()
if echoReq.GetRequestType() == "LaunchRequest" {
if app.OnLaunch != nil {
app.OnLaunch(echoReq, echoResp)
}
} else if echoReq.GetRequestType() == "IntentRequest" {
if app.OnIntent != nil {
app.OnIntent(echoReq, echoResp)
}
} else if echoReq.GetRequestType() == "SessionEndedRequest" {
if app.OnSessionEnded != nil {
app.OnSessionEnded(echoReq, echoResp)
}
} else {
http.Error(w, "Invalid request.", http.StatusBadRequest)
}
json, _ := echoResp.String()
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.Write(json)
}
if app.Handler != nil {
handlerFunc = app.Handler
}
echoRouter.HandleFunc(uri, handlerFunc).Methods("POST")
case StdApplication:
pageRouter.HandleFunc(uri, app.Handler).Methods(app.Methods)
}
}
router.PathPrefix("/echo/").Handler(negroni.New(
negroni.HandlerFunc(validateRequest),
negroni.HandlerFunc(verifyJSON),
negroni.Wrap(echoRouter),
))
router.PathPrefix("/").Handler(negroni.New(
negroni.Wrap(pageRouter),
))
}
示例4: main
func main() {
flag.Parse()
store.Init()
p := func(name string, handler http.HandlerFunc) http.Handler {
return prometheus.InstrumentHandler(name, handler)
}
router := mux.NewRouter()
router.Handle("/metrics", prometheus.Handler())
router.Handle("/", p("/", home))
router.Handle("/login", p("/login", login))
router.Handle("/verify", p("/verify", verify))
apiRouter := mux.NewRouter()
apiRouter.Handle("/api/logout", p("/logout", logout))
apiRouter.Handle("/api/user", p("/user", user))
apiRouter.Handle("/api/user/project", p("/user/project", userProject))
apiRouter.Handle("/api/project", p("/project", project))
apiRouter.Handle("/api/project/member", p("/task/member", member))
apiRouter.Handle("/api/task", p("/task", task))
apiRouter.Handle("/api/task/worker", p("/task/worker", worker))
apiRouter.Handle("/api/milestone", p("/milestone", milestone))
apiRouter.Handle("/api/friend", p("/friend", friend))
apiRouter.Handle("/api/chat", p("/chat", chat))
apiRouter.HandleFunc("/api/ws", ws)
router.PathPrefix("/api").Handler(negroni.New(
negroni.HandlerFunc(apiMiddleware),
negroni.Wrap(apiRouter),
))
adminRouter := mux.NewRouter()
adminRouter.Handle("/api/admin/user", p("/admin/user", adminUser))
adminRouter.Handle("/api/admin/project", p("/admin/project", adminProject))
router.PathPrefix("/api/admin").Handler(negroni.New(
negroni.HandlerFunc(adminMiddleware),
negroni.Wrap(adminRouter),
))
go h.run()
n := negroni.Classic()
n.UseHandler(router)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
n.Run(":" + port)
}
示例5: main
func main() {
var err error
db, err = sqlx.Connect("postgres", "user=postgres password=postgres dbname=messenger sslmode=disable")
if err != nil {
log.Fatalln(err)
}
CreateSchema(false)
r := mux.NewRouter()
authBase := mux.NewRouter()
apiBase := mux.NewRouter()
auth := authBase.PathPrefix("/auth").Subrouter()
api := apiBase.PathPrefix("/api").Subrouter()
r.PathPrefix("/auth").Handler(negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.Wrap(authBase),
))
jwtSecret = "a very secret string"
// must be authenticated to use api routes
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
},
SigningMethod: jwt.SigningMethodHS256,
UserProperty: "jwt_user",
})
r.PathPrefix("/api").Handler(negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(apiBase),
))
// used to check if server is live
auth.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "pong")
}).Methods("POST")
auth.Path("/signup").HandlerFunc(Signup).Methods("POST")
auth.Path("/login").HandlerFunc(Login).Methods("POST")
api.Path("/messages").HandlerFunc(NewMessage).Methods("POST")
api.HandleFunc("/{user}/messages", GetUsersMessages).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
示例6: AddRoutes
// AddRoutes adds routes to a router instance. If there are middlewares defined
// for a route, a new negroni app is created and wrapped as a http.Handler
func AddRoutes(routes []Route, router *mux.Router) {
var (
handler http.Handler
n *negroni.Negroni
)
for _, route := range routes {
// Add any specified middlewares
if len(route.Middlewares) > 0 {
n = negroni.New()
for _, middleware := range route.Middlewares {
n.Use(middleware)
}
// Wrap the handler in the negroni app with middlewares
n.Use(negroni.Wrap(route.HandlerFunc))
handler = n
} else {
handler = route.HandlerFunc
}
router.Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
}
示例7: serverRun
func serverRun(cmd *cobra.Command, args []string) {
// MongoDB setup
CreateUniqueIndexes()
// Web Server Setup
CreateStore()
webRouter := CreateWebRouter()
teamRouter := CreateTeamRouter()
app := negroni.New()
webRouter.PathPrefix("/").Handler(negroni.New(
negroni.HandlerFunc(RequireLogin),
negroni.Wrap(teamRouter),
))
app.Use(negroni.NewLogger())
app.Use(negroni.NewStatic(http.Dir("static")))
app.Use(negroni.HandlerFunc(CheckSessionID))
app.UseHandler(webRouter)
l := log.New(os.Stdout, "[negroni] ", 0)
http_port := viper.GetString("server.http_port")
https_port := viper.GetString("server.https_port")
cert := viper.GetString("server.cert")
key := viper.GetString("server.key")
l.Printf("Server running at: https://%s:%s", viper.GetString("server.ip"), https_port)
go http.ListenAndServe(":"+http_port, http.HandlerFunc(redir))
l.Fatal(http.ListenAndServeTLS(":"+https_port, cert, key, app))
}
示例8: Init
func (ea *EventApi) Init(cfg map[string]*json.RawMessage) (err error) {
// setup the routes
ea.router = httprouter.New()
ea.router.GET("/", middleware.Join(
s.Server.ErrorWrap.Do(ea.list),
s.Server.CheckPerms("superuser", SESSION_EXPIRE)))
ea.router.POST("/", middleware.Join(
s.Server.ErrorWrap.Do(ea.post),
s.Server.CheckPerms("superuser", SESSION_EXPIRE)))
ea.router.GET("/:id", middleware.Join(
s.Server.ErrorWrap.Do(ea.get),
s.Server.CheckPerms("(superuser|admin-auth-event-${id})", SESSION_EXPIRE)))
ea.router.DELETE("/:id", middleware.Join(
s.Server.ErrorWrap.Do(ea.delete),
s.Server.CheckPerms("superuser", SESSION_EXPIRE)))
// setup prepared sql queries
if ea.insertStmt, err = s.Server.Db.PrepareNamed("INSERT INTO event (name, auth_method, auth_method_config) VALUES (:name, :auth_method, :auth_method_config) RETURNING id"); err != nil {
return
}
if ea.getStmt, err = s.Server.Db.Preparex("SELECT * FROM event WHERE id = $1"); err != nil {
return
}
if ea.delStmt, err = s.Server.Db.Preparex("DELETE FROM event WHERE id = $1"); err != nil {
return
}
// add the routes to the server
handler := negroni.New(negroni.Wrap(ea.router))
s.Server.Mux.OnMux("api/v1/event", handler)
return
}
示例9: Run
func (a *Api) Run() error {
globalMux := http.NewServeMux()
router := mux.NewRouter()
router.HandleFunc("/", a.index).Methods("GET")
router.HandleFunc("/create", a.create).Methods("POST")
router.HandleFunc("/ip", a.getIP).Methods("GET")
router.HandleFunc("/state", a.getState).Methods("GET")
router.HandleFunc("/start", a.start).Methods("GET")
router.HandleFunc("/kill", a.kill).Methods("GET")
router.HandleFunc("/remove", a.remove).Methods("GET")
router.HandleFunc("/restart", a.restart).Methods("GET")
router.HandleFunc("/stop", a.stop).Methods("GET")
// enable auth if token is present
if a.config.AuthToken != "" {
am := auth.NewAuthMiddleware(a.config.AuthToken)
globalMux.Handle("/", negroni.New(
negroni.HandlerFunc(am.Handler),
negroni.Wrap(http.Handler(router)),
))
} else {
globalMux.Handle("/", router)
}
log.Infof("rivet version %s", version.FULL_VERSION)
log.Infof("listening: addr=%s", a.config.ListenAddr)
n := negroni.New()
n.UseHandler(globalMux)
return http.ListenAndServe(a.config.ListenAddr, n)
}
示例10: SetAuthenticationRoutes
func SetAuthenticationRoutes(router *mux.Router) *mux.Router {
tokenRouter := mux.NewRouter()
tokenRouter.Handle("/api/auth/token/new", negroni.New(
negroni.HandlerFunc(controllers.Login),
)).Methods("POST")
tokenRouter.Handle("/api/auth/logout", negroni.New(
negroni.HandlerFunc(auth.RequireTokenAuthentication),
negroni.HandlerFunc(controllers.Logout),
))
tokenRouter.Handle("/api/auth/token/refresh", negroni.New(
negroni.HandlerFunc(auth.RequireTokenAuthentication),
negroni.HandlerFunc(controllers.RefreshToken),
)).Methods("GET")
tokenRouter.Handle("/api/auth/token/validate", negroni.New(
negroni.HandlerFunc(auth.RequireTokenAuthentication),
negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.WriteHeader(http.StatusOK)
}),
))
router.PathPrefix("/api/auth").Handler(negroni.New(
negroni.Wrap(tokenRouter),
))
return router
}
示例11: main
func main() {
router := http.NewServeMux()
// links our `api/admin` route to our protected handler
router.HandleFunc("/api/login", controllers.AuthHandler)
router.Handle("/api/users", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(http.HandlerFunc(controllers.UsersHandler)),
))
router.Handle("/api/authenticated", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(http.HandlerFunc(controllers.AuthenticateHandler)),
))
// serves the static files for angular js application as well as all other resources
router.Handle("/", http.FileServer(http.Dir("./static/")))
http.ListenAndServe(":8080", router)
}
示例12: main
// main is the entry point for lagann
func main() {
flag.Parse()
client = etcd.NewClient([]string{"http://" + *etcdmachine + ":4001"})
routing := http.NewServeMux()
usermux := routes.New()
n := negroni.Classic()
n.UseHandler(routing)
routing.HandleFunc(constants.ROOT_MUXPATH, root)
routing.HandleFunc(constants.REGISTER_URL, register)
routing.HandleFunc(constants.LOGIN_URL, login)
usermux.Post(constants.APP_CREATE_URL, createApp)
usermux.Post(constants.APP_SHARING_URL, addSharing)
auth, _ := auth.NewAuth("http://"+*etcdmachine+":4001", constants.ETCD_LAGANN_AUTHKEYS)
routing.Handle(constants.USER_MUXPATH, negroni.New(
auth,
negroni.Wrap(usermux),
))
n.Run(":3000")
}
示例13: BuildRoutes
// BuildRoutes returns the routes for the application.
func BuildRoutes() http.Handler {
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
router.HandleFunc("/login-success", LoginSuccessHandler)
router.HandleFunc("/verify", VerifyHandler)
router.HandleFunc("/logout", LogoutHandler)
router.HandleFunc("/game", GameHandler)
// profile routes with LoginRequiredMiddleware
profileRouter := mux.NewRouter()
profileRouter.HandleFunc("/profile", ProfileHandler)
router.PathPrefix("/profile").Handler(negroni.New(
negroni.HandlerFunc(LoginRequiredMiddleware),
negroni.Wrap(profileRouter),
))
// apply the base middleware to the main router
n := negroni.New(
negroni.HandlerFunc(CsrfMiddleware),
negroni.HandlerFunc(UserMiddleware),
)
n.UseHandler(router)
return n
}
示例14: router
func router(config clientConfig) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/", indexHandler(config))
r.Handle("/favicon.ico", http.NotFoundHandler())
authMiddleware := negroni.HandlerFunc(ShotgunAuthMiddleware(config))
entityRoutes := mux.NewRouter()
entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityGetHandler(config)).Methods("GET")
entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityUpdateHandler(config)).Methods("PATCH")
entityRoutes.Path("/{entity_type}/{id:[0-9]+}").
HandlerFunc(entityDeleteHandler(config)).Methods("DELETE")
entityRoutes.Path("/{entity_type}/{id:[0-9]+}/revive").
HandlerFunc(entityReviveHandler(config)).Methods("POST")
// entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
// HandlerFunc(entityGetFollowersHandler(config)).Methods("GET")
//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
// HandlerFunc(entityAddFollowersHandler(config)).Methods("POST")
//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers/{user_type}/{user_id:[0-9]+}").
// HandlerFunc(entityDeleteFollowersHandler(config)).Methods("DELETE")
entityRoutes.Path("/{entity_type}").HandlerFunc(entityGetAllHandler(config)).Methods("GET")
entityRoutes.Path("/{entity_type}").HandlerFunc(entityCreateHandler(config)).Methods("POST")
// Adds auth on the sub router so that / can be accessed freely.
r.PathPrefix("/{entity_type}").Handler(negroni.New(
authMiddleware,
negroni.Wrap(entityRoutes),
))
return r
}
示例15: StaticPathFallback
func StaticPathFallback(path string) http.Handler {
return negroni.New(
negroni.NewStatic(http.Dir(path)),
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = "/"
http.FileServer(http.Dir(path)).ServeHTTP(w, r)
})))
}