// In this bench we want to test middleware. // Context: middleware stack with 3 levels of context // Each middleware has 2 functions which just call next() func BenchmarkMiddleware(b *testing.B) { nextMw := func(w web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { next(w, r) } router := web.New(BenchContext{}) router.Middleware(nextMw) router.Middleware(nextMw) routerB := router.Subrouter(BenchContextB{}, "/b") routerB.Middleware(nextMw) routerB.Middleware(nextMw) routerC := routerB.Subrouter(BenchContextC{}, "/c") routerC.Middleware(nextMw) routerC.Middleware(nextMw) routerC.Get("/action", func(w web.ResponseWriter, r *web.Request) { fmt.Fprintf(w, "hello") }) rw, req := testRequest("GET", "/b/c/action") b.ResetTimer() for i := 0; i < b.N; i++ { router.ServeHTTP(rw, req) // if rw.Code != 200 { panic("no good") } } }
func StartServer(database *gorm.DB) { db = database router := web.New(Context{}). Middleware(web.LoggerMiddleware). Middleware((*Context).QueryVarsMiddleware). Middleware(CorsMiddleware). Get("/counter", (*Context).CounterHandler). Get("/counter/:code", (*Context).CounterByCodeHandler). Post("/counter/:code/tick", (*Context).CounterByCodeTickHandler). Put("/counter/:code/corr", (*Context).CounterByCodeCorrectHandler). Get("/counter/:code/events", (*Context).CounterByCodeEventsHandler). Get("/thermometer", (*Context).ThermometerHandler). Get("/thermometer/:code", (*Context).ThermometerByCodeHandler). Post("/thermometer/:code/reading", (*Context).ThermometerByCodeAddReadingHandler). Get("/thermometer/:code/readings", (*Context).ThermometerByCodeGetReadingsHandler). Get("/flag", (*Context).FlagHandler). Get("/flag/:code", (*Context).FlagByCodeHandler). Post("/flag/:code/state", (*Context).FlagByCodeChangeStateHandler). Get("/flag/:code/states", (*Context).FlagByCodeGetStatesHandler) e := http.ListenAndServe(":8080", router) tools.ErrorCheck(e) }
// InitRouter sets up the router (and subrouters). // It also includes the closure middleware where we load the global Settings reference into each request. func InitRouter(settings *helpers.Settings) *web.Router { router := web.New(Context{}) // A closure that effectively loads the Settings into every request. router.Middleware(func(c *Context, resp web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { c.Settings = settings next(resp, req) }) // Backend Route Initialization // Initialize the Gocraft Router with the basic context and routes router.Get("/ping", (*Context).Ping) router.Get("/handshake", (*Context).LoginHandshake) router.Get("/oauth2callback", (*Context).OAuthCallback) // Setup the /api subrouter. apiRouter := router.Subrouter(APIContext{}, "/v2") apiRouter.Middleware((*APIContext).OAuth) // All routes accepted apiRouter.Get("/authstatus", (*APIContext).AuthStatus) apiRouter.Get("/logout", (*APIContext).Logout) apiRouter.Get("/profile", (*APIContext).UserProfile) apiRouter.Get("/:*", (*APIContext).Proxy) // Frontend Route Initialization // Set up static file serving to load from the static folder. router.Middleware(web.StaticMiddleware("static", web.StaticOption{IndexFile: "index.html"})) return router }
func main() { router := web.New(Context{}). Middleware(web.LoggerMiddleware). Middleware(runnerMiddleware). Get("/", (*Context).SayHello) http.ListenAndServe("localhost:3000", router) }
func main() { runtime.MemProfileRate = 1 router := web.New(Context{}). Middleware((*Context).Middleware). Middleware((*Context).Middleware). Middleware((*Context).Middleware). Middleware((*Context).Middleware). Middleware((*Context).Middleware). Middleware((*Context).Middleware). Get("/action", (*Context).Action) rw := &NullWriter{} req, _ := http.NewRequest("GET", "/action", nil) // pprof.StartCPUProfile(f) // defer pprof.StopCPUProfile() for i := 0; i < 1; i += 1 { router.ServeHTTP(rw, req) } f, err := os.Create("myprof.out") if err != nil { log.Fatal(err) } pprof.WriteHeapProfile(f) f.Close() }
func (s *ErrorTestSuite) TestMultipleErrorHandlers2(c *C) { router := web.New(Context{}) router.Get("/action", (*Context).ErrorAction) admin := router.Subrouter(AdminContext{}, "/admin") admin.Error((*AdminContext).ErrorHandler) admin.Get("/action", (*AdminContext).ErrorAction) api := router.Subrouter(ApiContext{}, "/api") api.Error((*ApiContext).ErrorHandler) api.Get("/action", (*ApiContext).ErrorAction) rw, req := newTestRequest("GET", "/action") router.ServeHTTP(rw, req) c.Assert(strings.TrimSpace(string(rw.Body.Bytes())), Equals, "Application Error") c.Assert(rw.Code, Equals, http.StatusInternalServerError) rw, req = newTestRequest("GET", "/admin/action") router.ServeHTTP(rw, req) c.Assert(strings.TrimSpace(string(rw.Body.Bytes())), Equals, "Admin Error") c.Assert(rw.Code, Equals, http.StatusInternalServerError) rw, req = newTestRequest("GET", "/api/action") router.ServeHTTP(rw, req) c.Assert(strings.TrimSpace(string(rw.Body.Bytes())), Equals, "Api Error") c.Assert(rw.Code, Equals, http.StatusInternalServerError) }
func BenchmarkGocraftWeb_Composite(b *testing.B) { namespaces, resources, requests := resourceSetup(10) nextMw := func(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { next(rw, r) } router := web.New(BenchContext{}) router.Middleware(func(c *BenchContext, rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { c.MyField = r.URL.Path next(rw, r) }) router.Middleware(nextMw) router.Middleware(nextMw) for _, ns := range namespaces { subrouter := router.Subrouter(BenchContextB{}, "/"+ns) subrouter.Middleware(nextMw) subrouter.Middleware(nextMw) subrouter.Middleware(nextMw) for _, res := range resources { subrouter.Get("/"+res, (*BenchContextB).Action) subrouter.Post("/"+res, (*BenchContextB).Action) subrouter.Get("/"+res+"/:id", (*BenchContextB).Action) subrouter.Put("/"+res+"/:id", (*BenchContextB).Action) subrouter.Delete("/"+res+"/:id", (*BenchContextB).Action) } } benchmarkRoutes(b, router, requests) }
func main() { router := web.New(Context{}). // Create your router Middleware(web.LoggerMiddleware). // Use some included middleware Middleware(web.ShowErrorsMiddleware). // ... Middleware((*Context).SetHelloCount). // Your own middleware! Get("/", (*Context).SayHello) // Add a route http.ListenAndServe("localhost:3000", router) // Start the server! }
// InitRouter sets up the router (and subrouters). // It also includes the closure middleware where we load the global Settings reference into each request. func InitRouter(settings *helpers.Settings) *web.Router { if settings == nil { return nil } router := web.New(Context{}) // A closure that effectively loads the Settings into every request. router.Middleware(func(c *Context, resp web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { c.Settings = settings next(resp, req) }) // Backend Route Initialization // Initialize the Gocraft Router with the basic context and routes router.Get("/ping", (*Context).Ping) router.Get("/handshake", (*Context).LoginHandshake) router.Get("/oauth2callback", (*Context).OAuthCallback) // Secure all the other routes secureRouter := router.Subrouter(SecureContext{}, "/") // Setup the /api subrouter. apiRouter := secureRouter.Subrouter(APIContext{}, "/v2") apiRouter.Middleware((*APIContext).OAuth) // All routes accepted apiRouter.Get("/authstatus", (*APIContext).AuthStatus) apiRouter.Get("/logout", (*APIContext).Logout) apiRouter.Get("/profile", (*APIContext).UserProfile) apiRouter.Get("/:*", (*APIContext).APIProxy) apiRouter.Put("/:*", (*APIContext).APIProxy) apiRouter.Post("/:*", (*APIContext).APIProxy) apiRouter.Delete("/:*", (*APIContext).APIProxy) // Setup the /uaa subrouter. uaaRouter := secureRouter.Subrouter(UAAContext{}, "/uaa") uaaRouter.Middleware((*UAAContext).OAuth) uaaRouter.Get("/userinfo", (*UAAContext).UserInfo) uaaRouter.Post("/Users", (*UAAContext).QueryUser) if settings.PProfEnabled { // Setup the /pprof subrouter. pprofRouter := secureRouter.Subrouter(PProfContext{}, "/debug/pprof") pprofRouter.Get("/", (*PProfContext).Index) pprofRouter.Get("/heap", (*PProfContext).Heap) pprofRouter.Get("/goroutine", (*PProfContext).Goroutine) pprofRouter.Get("/threadcreate", (*PProfContext).Threadcreate) pprofRouter.Get("/block", (*PProfContext).Threadcreate) pprofRouter.Get("/profile", (*PProfContext).Profile) pprofRouter.Get("/symbol", (*PProfContext).Symbol) } // Frontend Route Initialization // Set up static file serving to load from the static folder. router.Middleware(web.StaticMiddleware("static", web.StaticOption{IndexFile: "index.html"})) return router }
func main() { router := web.New(Context{}). // Create your router Middleware(web.LoggerMiddleware). // Use some included middleware Middleware(web.ShowErrorsMiddleware). // ... Middleware((*Context).Recording). // Your own middleware! Get("/", (*Context).Root). // Add a route Get("/stats", (*Context).RetrieveStats) // Add a route http.ListenAndServe("localhost:3001", router) // Start the server! }
func (s *NotFoundTestSuite) TestWithRootContext(c *C) { router := web.New(Context{}) router.NotFound((*Context).HandlerWithContext) rw, req := newTestRequest("GET", "/this_path_doesnt_exist") router.ServeHTTP(rw, req) c.Assert(strings.TrimSpace(string(rw.Body.Bytes())), Equals, "My Not Found With Context") c.Assert(rw.Code, Equals, http.StatusNotFound) }
func (s *MiddlewareTestSuite) TestSameNamespace(c *C) { router := web.New(Context{}) admin := router.Subrouter(AdminContext{}, "/") admin.Get("/action", (*AdminContext).B) rw, req := newTestRequest("GET", "/action") router.ServeHTTP(rw, req) assertResponse(c, rw, "admin-B", 200) }
func (s *MiddlewareTestSuite) TestNoNext(c *C) { router := web.New(Context{}) router.Middleware((*Context).mwNoNext) router.Get("/action", (*Context).A) rw, req := newTestRequest("GET", "/action") router.ServeHTTP(rw, req) assertResponse(c, rw, "context-mw-NoNext", 200) }
func initRouter() *web.Router { router := web.New(Context{}) router.Middleware(LogMiddleware) router.Middleware(web.ShowErrorsMiddleware) // router.Middleware((*Context).OutputJson) // router.Get("/v1/clean", (*Context).Clean) return router }
// InitRouter sets up the router (and subrouters). // It also includes the closure middleware where we load the global Settings reference into each request. func InitRouter(settings *helpers.Settings, templates *template.Template) *web.Router { if settings == nil { return nil } router := web.New(Context{}) // A closure that effectively loads the Settings into every request. router.Middleware(func(c *Context, resp web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { c.Settings = settings c.templates = templates next(resp, req) }) router.Get("/", (*Context).Index) // Backend Route Initialization // Initialize the Gocraft Router with the basic context and routes router.Get("/ping", (*Context).Ping) router.Get("/handshake", (*Context).LoginHandshake) router.Get("/oauth2callback", (*Context).OAuthCallback) // Secure all the other routes secureRouter := router.Subrouter(SecureContext{}, "/") // Setup the /api subrouter. apiRouter := secureRouter.Subrouter(APIContext{}, "/v2") apiRouter.Middleware((*APIContext).OAuth) // All routes accepted apiRouter.Get("/authstatus", (*APIContext).AuthStatus) apiRouter.Get("/logout", (*APIContext).Logout) apiRouter.Get("/profile", (*APIContext).UserProfile) apiRouter.Get("/:*", (*APIContext).APIProxy) apiRouter.Put("/:*", (*APIContext).APIProxy) apiRouter.Post("/:*", (*APIContext).APIProxy) apiRouter.Delete("/:*", (*APIContext).APIProxy) // Setup the /uaa subrouter. uaaRouter := secureRouter.Subrouter(UAAContext{}, "/uaa") uaaRouter.Middleware((*UAAContext).OAuth) uaaRouter.Get("/userinfo", (*UAAContext).UserInfo) // Setup the /log subrouter. logRouter := secureRouter.Subrouter(LogContext{}, "/log") logRouter.Middleware((*LogContext).OAuth) logRouter.Get("/recent", (*LogContext).RecentLogs) // Add auth middleware router.Middleware((*Context).LoginRequired) // Frontend Route Initialization // Set up static file serving to load from the static folder. router.Middleware(web.StaticMiddleware("static")) return router }
func NewHandler(conf Config) (http.Handler, error) { router := web.New(conf.GlobalContext) if conf.GlobalMiddleware != nil { addMiddleware(router, conf.GlobalMiddleware) } err := addRoutes(router, conf.GlobalContext, conf.Routes) if err != nil { return nil, err } return router, nil }
func (s *MiddlewareTestSuite) TestTicketsC(c *C) { router := web.New(Context{}) router.Middleware((*Context).mwAlpha) admin := router.Subrouter(AdminContext{}, "/admin") tickets := admin.Subrouter(TicketsContext{}, "/tickets") tickets.Get("/action", (*TicketsContext).D) rw, req := newTestRequest("GET", "/admin/tickets/action") router.ServeHTTP(rw, req) assertResponse(c, rw, "context-mw-Alpha tickets-D", 200) }
func (s *ErrorTestSuite) TestConsistentContext(c *C) { router := web.New(Context{}) router.Error((*Context).ErrorHandler) admin := router.Subrouter(Context{}, "/admin") admin.Error((*Context).ErrorHandlerSecondary) admin.Get("/foo", (*Context).ErrorAction) rw, req := newTestRequest("GET", "/admin/foo") router.ServeHTTP(rw, req) assertResponse(c, rw, "My Secondary Error", 500) }
func NewStaticServer(root string, port int) *Server { server := Server{} server.Root = root server.Port = port server.Router = web.New(emptyContext{}) // NOTE: the middleware does NOT list folder, it is said to avoid content length problem server.Router.Middleware(web.LoggerMiddleware) server.Router.Middleware(web.StaticMiddleware(server.Root, web.StaticOption{IndexFile: "index.html"})) return &server }
// Simplest benchmark ever. // One router, one route. No middleware. Just calling the action. func BenchmarkSimple(b *testing.B) { router := web.New(BenchContext{}) router.Get("/action", (*BenchContext).Action) rw, req := testRequest("GET", "/action") b.ResetTimer() for i := 0; i < b.N; i++ { router.ServeHTTP(rw, req) } }
func BenchmarkGocraftWeb_Simple(b *testing.B) { router := web.New(BenchContext{}) router.Get("/action", gocraftWebHandler) rw, req := testRequest("GET", "/action") b.ResetTimer() for i := 0; i < b.N; i++ { router.ServeHTTP(rw, req) } }
func NewAyiServer(port int) *Server { server := Server{} server.Port = port server.Router = web.New(ayiContext{}) server.Router.Middleware(web.LoggerMiddleware) box := rice.MustFindBox("app-web-public") // NOTE: index file does not work, because isDir return false server.Router.Middleware(web.StaticMiddlewareFromDir(box.HTTPBox(), web.StaticOption{})) server.Router.Get("/", (*ayiContext).Index) return &server }
func (s *ErrorTestSuite) TestNonRootMiddlewarePanic(c *C) { router := web.New(Context{}) router.Error((*Context).ErrorHandler) admin := router.Subrouter(AdminContext{}, "/admin") admin.Middleware((*AdminContext).ErrorMiddleware) admin.Error((*AdminContext).ErrorHandler) admin.Get("/action", (*AdminContext).ErrorAction) rw, req := newTestRequest("GET", "/admin/action") router.ServeHTTP(rw, req) assertResponse(c, rw, "Admin Error", 500) }
func (s *MiddlewareTestSuite) TestSameContext(c *C) { router := web.New(Context{}) router.Middleware((*Context).mwAlpha). Middleware((*Context).mwBeta) admin := router.Subrouter(Context{}, "/admin") admin.Middleware((*Context).mwGamma) admin.Get("/foo", (*Context).A) rw, req := newTestRequest("GET", "/admin/foo") router.ServeHTTP(rw, req) assertResponse(c, rw, "context-mw-Alpha context-mw-Beta context-mw-Gamma context-A", 200) }
func main() { schemaDir = getSchemaDir() router := web.New(Context{}). Middleware(web.LoggerMiddleware). // Use some included middleware Middleware(web.ShowErrorsMiddleware). // ... Middleware(web.StaticMiddleware("www")). Post("/api/v0/keys", (*Context).createKeyValue) http.ListenAndServe("localhost:8080", router) }
func initGocraft() { var ctx struct{} h := gocraft.New(ctx) h.Get("/", func(w gocraft.ResponseWriter, r *gocraft.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "Hello, World") }) h.Get("/:name", func(w gocraft.ResponseWriter, r *gocraft.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "Hello, %s", r.PathParams["name"]) }) registerHandler("gocraft", h) }
func (s *MiddlewareTestSuite) TestFlatNoMiddleware(c *C) { router := web.New(Context{}) router.Get("/action", (*Context).A) router.Get("/action_z", (*Context).Z) rw, req := newTestRequest("GET", "/action") router.ServeHTTP(rw, req) assertResponse(c, rw, "context-A", 200) rw, req = newTestRequest("GET", "/action_z") router.ServeHTTP(rw, req) assertResponse(c, rw, "context-Z", 200) }
// // Benchmarks for gocraft/web: // func BenchmarkGocraftWebSimple(b *testing.B) { router := web.New(BenchContext{}) router.Get("/action", func(rw web.ResponseWriter, r *web.Request) { fmt.Fprintf(rw, "hello") }) rw, req := testRequest("GET", "/action") b.ResetTimer() for i := 0; i < b.N; i++ { router.ServeHTTP(rw, req) } }
func main() { router := web.New(Context{}). // Create your router Middleware(web.LoggerMiddleware). // Use some included middleware Middleware(web.ShowErrorsMiddleware). // ... Middleware((*Context).UserRequired). Get("/healthcheck", (*Context).Healthcheck). Get("/api/v1/users/:uuid", (*Context).GetUserInfo). // Add a route Get("/signup", (*Context).RedirectOauth) // Add a route port := os.Getenv("PORT") if port == "" { port = "80" } http.ListenAndServe("0.0.0.0:"+port, router) // Start the server! }
func (s *NotFoundTestSuite) TestBadMethod(c *C) { router := web.New(Context{}) rw, req := newTestRequest("POOP", "/this_path_doesnt_exist") router.ServeHTTP(rw, req) c.Assert(strings.TrimSpace(string(rw.Body.Bytes())), Equals, "Not Found") c.Assert(rw.Code, Equals, http.StatusNotFound) }