コード例 #1
0
ファイル: speed_test.go プロジェクト: nikai3d/web
// 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") }
	}
}
コード例 #2
0
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)
}
コード例 #3
0
ファイル: routes.go プロジェクト: goodnightjj/cf-deck
// 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
}
コード例 #4
0
ファイル: main.go プロジェクト: stoplightio/fresh
func main() {
	router := web.New(Context{}).
		Middleware(web.LoggerMiddleware).
		Middleware(runnerMiddleware).
		Get("/", (*Context).SayHello)
	http.ListenAndServe("localhost:3000", router)
}
コード例 #5
0
ファイル: main.go プロジェクト: hannobraun/web
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()
}
コード例 #6
0
ファイル: error_test.go プロジェクト: kristian-puccio/web
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)
}
コード例 #7
0
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)
}
コード例 #8
0
ファイル: main.go プロジェクト: kristian-puccio/web
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!
}
コード例 #9
0
ファイル: routes.go プロジェクト: dlapiduz/cf-deck
// 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
}
コード例 #10
0
ファイル: server.go プロジェクト: krisrang/fancypants
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!
}
コード例 #11
0
ファイル: not_found_test.go プロジェクト: kristian-puccio/web
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)
}
コード例 #12
0
ファイル: middleware_test.go プロジェクト: nikai3d/web
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)
}
コード例 #13
0
ファイル: middleware_test.go プロジェクト: nikai3d/web
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)
}
コード例 #14
0
ファイル: router.go プロジェクト: ahjdzx/dis
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
}
コード例 #15
0
ファイル: routes.go プロジェクト: 18F/cg-dashboard
// 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
}
コード例 #16
0
ファイル: detour.go プロジェクト: classdojo/detour
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
}
コード例 #17
0
ファイル: middleware_test.go プロジェクト: nikai3d/web
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)
}
コード例 #18
0
ファイル: error_test.go プロジェクト: kristian-puccio/web
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)
}
コード例 #19
0
ファイル: server.go プロジェクト: dyweb/Ayi
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
}
コード例 #20
0
ファイル: speed_test.go プロジェクト: nikai3d/web
// 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)
	}
}
コード例 #21
0
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)
	}
}
コード例 #22
0
ファイル: server.go プロジェクト: dyweb/Ayi
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
}
コード例 #23
0
ファイル: error_test.go プロジェクト: kristian-puccio/web
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)
}
コード例 #24
0
ファイル: middleware_test.go プロジェクト: nikai3d/web
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)
}
コード例 #25
0
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)
}
コード例 #26
0
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)
}
コード例 #27
0
ファイル: middleware_test.go プロジェクト: nikai3d/web
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)
}
コード例 #28
0
//
// 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)
	}
}
コード例 #29
0
ファイル: server.go プロジェクト: crossyio/crossyinfo-service
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!
}
コード例 #30
-1
ファイル: not_found_test.go プロジェクト: kristian-puccio/web
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)
}