Example #1
0
// 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
}
Example #2
0
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)))
}
Example #3
0
File: main.go Project: rmg/tyk
// 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)
		}

	}
}
Example #4
0
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()

}
Example #5
0
// 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)
}
Example #6
0
// 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
}
Example #7
0
// 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
}
Example #8
0
// 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
}
Example #9
0
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
}
Example #10
0
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)

}
Example #11
0
File: web.go Project: beppeben/m3m3
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())
		}
	}()

}
Example #12
0
func Stack() *App {
	app := App{R: httprouter.New()}
	app.Stack = alice.New(app.logger, app.recovery)
	app.Context = make(map[string]interface{})

	return &app
}
Example #13
0
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)))
}
Example #14
0
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)
	}
}
Example #15
0
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)
}
Example #16
0
func main() {
	Portfolios = make(map[float32]Portfolio)

	// HTTP request multiplexer
	// mux.Router matches incoming requests against a list of registered routes
	// and calls a handler for the route that matches the URL
	r := mux.NewRouter()

	s := rpc.NewServer()
	s.RegisterCodec(json.NewCodec(), "application/json")

	stockDealer := new(StockDealer)
	s.RegisterService(stockDealer, "")

	// middle ware: organizing  hared functionalities
	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)
		})

	r.Handle("/rpc", chain.Then(s))
	fmt.Println("Server listening on 8080")
	log.Fatal(http.ListenAndServe(":8080", r))
}
func main() {

	//stock account Initialization
	var st = (new(StockAccounts))

	//Trade Id random generator
	tradeId = rand.Intn(99999) + 1

	//start listening
	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(":8070", server))

}
Example #18
0
// RunServer starts the server that returns the container info and blocks.
func RunServer() error {
	info, _ = getContainerInfo()
	ci := &ContainerInfo{}
	c := alice.New(LoggingHandler)
	http.Handle("/info", c.Then(ci))
	return http.ListenAndServe(":8080", nil)
}
Example #19
0
func main() {
	var conf config.Config
	if _, err := toml.DecodeFile("configs.toml", &conf); err != nil {
		log.Fatal(err)
	}
	fmt.Println(conf)

	// pqStr := "user="******" password='******' dbname=remindbot host=localhost sslmode=disable"
	// fmt.Println(pqStr)

	// db, err := sql.Open("postgres", pqStr)
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// defer db.Close()

	buf := bytes.NewBuffer(nil)
	ac := handlers.NewAppContext(nil, conf, buf)
	stack := alice.New()

	r := router.New()
	r.POST("/reminders", stack.ThenFunc(ac.CommandHandler))

	fmt.Println("Server starting at port 8080.")
	http.ListenAndServe(":8080", r)
}
Example #20
0
//Util to convert HTTPRouter handler to net/http handler
func WrapHandler(hr func(http.ResponseWriter, *http.Request)) httprouter.Handle {
	h := alice.New(context.ClearHandler).ThenFunc(hr)
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		context.Set(r, "params", ps)
		h.ServeHTTP(w, r)
	}
}
Example #21
0
func main() {

	//setup a http router (any one would work)
	router := httprouter.New()

	//setup our role mapper
	roleMapper := rbac.NewRoleMapper()

	//setup our 'user db'
	udb := userdb.NewUserDB()
	udb.AddUser("bob", []string{"admin"})
	udb.AddUser("phil", []string{"backoffice", "users.list"})
	udb.AddUser("joan", []string{"viewer"})

	authChain := alice.New(createRBACHandler(udb, roleMapper))

	router.Handler("GET", "/", authChain.Then(urlPage()))
	roleMapper.AddMethodMapping("/admin", "GET", []string{"admin"})
	router.Handler("GET", "/admin", authChain.Then(urlPage()))
	roleMapper.AddMethodMapping("/orders", "GET", []string{"admin", "backoffice", "orders.list"})
	router.Handler("GET", "/orders", authChain.Then(urlPage()))
	roleMapper.AddMethodMapping("/users", "GET", []string{"admin", "users.list"})
	router.Handler("GET", "/users", authChain.Then(urlPage()))
	roleMapper.AddMethodMapping("/news", "GET", []string{"admin", "backoffice", "viewer", "news.list"})
	router.Handler("GET", "/news", authChain.Then(urlPage()))

	log.Fatal(http.ListenAndServe(":8080", router))
}
Example #22
0
func Start(port int, configuration *config.Config) {

	portString := ":" + strconv.Itoa(port)
	dropFavicon := middleware.NewFaviconMiddleware(configuration)

	// cache
	interrogateRequest := middleware.NewInterrogatorMiddleware(configuration)
	selectBackend := middleware.NewSelectBackendMiddleware(configuration)
	rejectUnsupportedMediaTypes := middleware.NewRejectUnsupportedMediaTypeMiddleware(configuration)
	passthrough := middleware.NewPassthroughMiddleware(configuration)

	// cookieParser
	backendProxy := middleware.NewBackendProxyMiddleware(configuration)

	chain := alice.New(dropFavicon.Handle,
		interrogateRequest.Handle,
		selectBackend.Handle,
		rejectUnsupportedMediaTypes.Handle,
		passthrough.Handle,
		backendProxy.Handle).ThenFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		target := context.Get(r, "renderedTarget")
		if target != nil {
			renderedTarget := target.(string)
			w.Write([]byte(renderedTarget))
		}
	}))

	http.ListenAndServe(portString, chain)
}
Example #23
0
func init() {

	encryptionKey, err := config.Conf.GetString("encryption-key")
	if err != nil {
		panic("Failed to get encryption-key:" + err.Error())
	}

	//	rate, err := limiter.NewRateFromFormatted("5-S")
	//	if err != nil {
	//		panic(err)
	//	}
	//
	//	//TODO - exchange for redis store
	//	store := limiter.NewMemoryStoreWithOptions(limiter.StoreOptions{
	//		Prefix:          "byrnedosvc",
	//		CleanUpInterval: 30 * time.Second,
	//	})
	//	limiterMw := limiter.NewHTTPMiddleware(limiter.NewLimiter(store, rate))

	var rtr = httprouter.New()
	controllers.RegisterRoutes(rtr, webcontrollers.NewUsersController(encryptionKey))

	//alice is a tiny package to chain middlewares.
	handlerChain := alice.New(
		//limiterMw.Handler,
		middleware.LogTime,
		middleware.RecoverHandler,
		middleware.AcceptJsonHandler,
	).Then(rtr)

	http.Handle("/", handlerChain)
}
Example #24
0
func main() {
	// Create a REST API resource index
	index := resource.NewIndex()

	// Add a resource on /users[/:user_id]
	users := index.Bind("users", user, mem.NewHandler(), resource.Conf{
		// We allow all REST methods
		// (rest.ReadWrite is a shortcut for []resource.Mode{resource.Create, resource.Read, resource.Update, resource.Delete, resource,List})
		AllowedModes: resource.ReadWrite,
	})

	// Bind a sub resource on /users/:user_id/posts[/:post_id]
	// and reference the user on each post using the "user" field of the posts resource.
	posts := users.Bind("posts", "user", post, mem.NewHandler(), resource.Conf{
		// Posts can only be read, created and deleted, not updated
		AllowedModes: []resource.Mode{resource.Read, resource.List, resource.Create, resource.Delete},
	})

	// Add a friendly alias to public posts
	// (equivalent to /users/:user_id/posts?filter={"published":true})
	posts.Alias("public", url.Values{"filter": []string{"{\"published\":true}"}})

	// Create API HTTP handler for the resource graph
	api, err := rest.NewHandler(index)
	if err != nil {
		log.Fatalf("Invalid API configuration: %s", err)
	}

	c := alice.New()

	// Add close notifier handler so context is cancelled when the client closes
	// the connection
	// c.Append(xhandler.CloseHandler)

	// Add timeout handler
	// c.Append(xhandler.TimeoutHandler(2 * time.Second))

	// Install a logger (see https://github.com/rs/xlog)
	c = c.Append(xlog.NewHandler(xlog.Config{}))
	resource.LoggerLevel = resource.LogLevelDebug
	resource.Logger = func(ctx context.Context, level resource.LogLevel, msg string, fields map[string]interface{}) {
		xlog.FromContext(ctx).OutputF(xlog.Level(level), 2, msg, fields)
	}

	// Log API access
	c = c.Append(xaccess.NewHandler())

	// Add CORS support with passthrough option on so rest-layer can still
	// handle OPTIONS method
	c = c.Append(cors.New(cors.Options{OptionsPassthrough: true}).Handler)

	// Bind the API under /api/ path
	http.Handle("/api/", http.StripPrefix("/api/", c.Then(api)))

	// Serve it
	log.Print("Serving API on http://localhost:8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
func main() {

	//Creating stock records
	var st = (new(StockRecords))

	//TradeID Initialization
	tradeId = 0

	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(":1333", server))

}
Example #26
0
func main() {
	commonHandlers := alice.New(loggingHandler, recoverHandler)
	//commonHandlers := alice.New(loggingHandler)
	//http.HandleFunc("/", webUploadHandler)
	http.Handle("/", commonHandlers.ThenFunc(webUploadHandler))
	http.ListenAndServe(":8080", nil)
}
Example #27
0
func main() {

	logrus.SetLevel(logrus.DebugLevel)

	mws := []alice.Constructor{
		logging.NewHandler,
		func(handler http.Handler) http.Handler { return filters.RenderSetupHandler(handler) },
	}

	appHandler := alice.New(mws...).Then(app.BuildRouter())
	http.Handle("/", appHandler)

	port := getEnvVar("PORT", config.DefaultServerPort)

	addr := fmt.Sprintf(":%s", port)
	logrus.Infof("Server listening on port %s", port)
	http.ListenAndServe(addr, nil)

	/*
		twitterClient := twitter.NewTwitterClient()
		v := url.Values{
			"count":       {"200"},
			"include_rts": {"false"},
		}

		tweets := twitterClient.GetTweets(v)

		mongoClient := &mongo.MongoClient{}
		mongoClient.SaveTweet(tweets)

	*/
}
Example #28
0
func ExampleConstructor() {
	chain := alice.New(Constructor("example")).ThenFunc(handler)

	err := http.ListenAndServe("127.0.0.1:3000", chain)
	if err != nil {
		log.Panicf("unable to start: %s", err)
	}
}
Example #29
0
func main() {
	c := alice.New(logger())
	r := mux.NewRouter()
	r.Handle("/", c.ThenFunc(getIndex)).Methods("GET")
	r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
	log.Println("http listen and server on port 3000")
	log.Fatal(http.ListenAndServe(":3000", r))
}
// CompaniesInterfaceRoutes is routing for /companies root endpoint
func CompaniesInterfaceRoutes(r *mux.Router, i CompaniesInterface) {
	r.Handle("/companies", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.GetCompanyList))).Methods("GET")
	r.Handle("/companies", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.Post))).Methods("POST")
	r.Handle("/companies/{globalId}", alice.New(newOauth2oauth_2_0Middleware([]string{"company:read", "company:admin"}).Handler).Then(http.HandlerFunc(i.globalIdGet))).Methods("GET")
	r.Handle("/companies/{globalId}", alice.New(newOauth2oauth_2_0Middleware([]string{"company:admin"}).Handler).Then(http.HandlerFunc(i.globalIdPut))).Methods("PUT")
	r.Handle("/companies/{globalId}/info", alice.New(newOauth2oauth_2_0Middleware([]string{"company:info"}).Handler).Then(http.HandlerFunc(i.globalIdinfoGet))).Methods("GET")
	r.Handle("/companies/{globalId}/validate", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.globalIdvalidateGet))).Methods("GET")
	r.Handle("/companies/{globalId}/contracts", alice.New(newOauth2oauth_2_0Middleware([]string{"company:admin", "company:contracts:read"}).Handler).Then(http.HandlerFunc(i.globalIdcontractsGet))).Methods("GET")
	r.Handle("/companies/{globalId}/contracts", alice.New(newOauth2oauth_2_0Middleware([]string{"company:admin", "company:contracts:write"}).Handler).Then(http.HandlerFunc(i.RegisterNewContract))).Methods("POST")
}