// NewHTTP returns a new instance of the HTTPDrive struct. func NewHTTP(before []DriveMiddleware, after []DriveMiddleware) *HTTPDrive { var drive HTTPDrive drive.TreeMux = httptreemux.New() drive.globalMW = LiftWM(before...) drive.globalMWAfter = LiftWM(after...) return &drive }
func loadHttpTreeMux(routes []route) http.Handler { router := httptreemux.New() for _, route := range routes { router.Handle(route.method, route.path, httpTreeMuxHandler) } return router }
// New create an Web value that handle a set of routes for the application. // You can provide any number of middleware and they'll be used to wrap every // request handler. func New(mw ...Middleware) *Web { return &Web{ TreeMux: httptreemux.New(), Ctx: make(map[string]interface{}), mw: mw, } }
func buildApp(z *Zest) error { deps := usecases.DependencyDirectory.Get() store := infrastructure.NewGormStore() accountRepo := resources.NewAccountRepo(store) aclRepo := resources.NewAclRepo(store) sessionRepo := resources.NewSessionRepo(store) deps = append( deps, store, accountRepo, aclRepo, sessionRepo, httptreemux.New(), infrastructure.NewRender(), infrastructure.NewCacheStore(), usecases.NewPermissionCacheInter(accountRepo, aclRepo, infrastructure.NewCacheStore(), infrastructure.NewCacheStore()), usecases.NewSessionCacheInter(sessionRepo, infrastructure.NewLRUCacheStore(1024)), usecases.NewRouteDirectory, usecases.NewPermissionInter, ) z.Injector.RegisterMultiple(deps) err := z.Injector.Populate() if err != nil { return err } return nil }
// NewMux returns a Mux. func NewMux() ServeMux { r := httptreemux.New() r.EscapeAddedRoutes = true return &mux{ router: r, handles: make(map[string]MuxHandler), } }
// New creates a new Router and returns it func New() *Router { r := &Router{} r.index = make(map[string]string) r.prefix = "/" r.router = httptreemux.New() r.router.NotFoundHandler = http.HandlerFunc(r.notFoundHandler) return r }
func (s *Server) Init() { s.logger = log.New(os.Stdout, "[GoWebApp] ", 0) mainController := controllers.NewMainController() s.router = httptreemux.New() s.router.GET("/", mainController.GetHandler) s.router.GET("/_version", mainController.GetVersionHandler) s.httpServer = negroni.Classic() s.httpServer.UseHandler(s.router) }
func (s *Server) initRoutes() { s.router = httptreemux.New() s.router.GET("/", s.healthCheck) s.router.GET("/healthcheck", s.healthCheck) s.router.POST("/api/item-schemas", transaction.Handle(s.createItemSchema)) s.router.GET("/api/item-schemas", transaction.Handle(s.findItemSchema)) s.router.GET("/api/item-schemas/findOne", transaction.Handle(s.findOneItemSchema)) s.router.GET("/api/item-schemas/:collectionName", transaction.Handle(s.findItemSchemaByCollectionName)) s.router.DELETE("/api/item-schemas/:collectionName", transaction.Handle(s.deleteItemSchemaByCollectionName)) s.router.POST("/api/:collectionName", s.createResource) s.router.GET("/api/:collectionName", s.findResource) s.router.GET("/api/:collectionName/findOne", s.findOneResource) s.router.GET("/api/:collectionName/:resourceId", s.findResourceById) s.router.DELETE("/api/:collectionName/:resourceId", s.deleteResourceById) }
func main() { // get config var port := envMustGet("JUNO_PORT") murl := envMustGet("JUNO_MONGO_URL") // initialize mongo s := storage.MgoMustConnect(murl) defer s.Close() // controller have to work with storage c := controller.New(s) // init router. httptreemux is fast and convinient r := httptreemux.New() // some of the endpoints are available in anonymous mode and some of them aren't. // we can perform different middleware operations - with auth checks and without. // build middleware that creates context and pass it to handlers rc := middle.Context(r, s) // add version rc = middle.Version(rc, VER) rc.Handle("POST", "/user", c.UserCreate) rc.Handle("GET", "/user/:userid/confirm", c.UserConfirm) rc.Handle("GET", "/profile/:profid", c.ProfileGet) rc.Handle("GET", "/profile/all", c.ProfileAll) // Add middleware that checks authentication. ra := middle.Authentication(rc, s) ra.Handle("PUT", "/profile", c.ProfileUpdate) ra.Handle("GET", "/profile/:profid/history", c.ProfileHistory) // add middleware that decorates router and checks that Content-Type is application/json rj := middle.JSONContentType(r) // Fire up the server log.Panic(http.ListenAndServe("localhost:"+port, rj)) }
func loadHttpTreeMuxSingle(method, path string, handler httptreemux.HandlerFunc) http.Handler { router := httptreemux.New() router.Handle(method, path, handler) return router }
// NewMux returns a Mux. func NewMux() ServeMux { return &mux{ router: httptreemux.New(), handles: make(map[string]MuxHandler), } }
// New create an App value that handle a set of routes for the application. // You can provide any number of middleware and they'll be used to wrap every // request handler. func New(mw ...Middleware) *App { return &App{ TreeMux: httptreemux.New(), mw: mw, } }
func starthttpTreeMux() { mux := httptreemux.New() mux.GET("/hello", httpTreeMuxHandler) http.ListenAndServe(":"+strconv.Itoa(port), mux) }
// New create an App value that handle a set of routes for the application. func New() *App { return &App{ TreeMux: httptreemux.New(), } }
func main() { // Setup var err error // GOMAXPROCS - Maybe not needed runtime.GOMAXPROCS(runtime.NumCPU()) // Write log to file if the log flag was provided if flags.Log != "" { logFile, err := os.OpenFile(flags.Log, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatal("Error: Couldn't open log file: " + err.Error()) } defer logFile.Close() log.SetOutput(logFile) } // Configuration is read from config.json by loading the configuration package // Database err = database.Initialize() if err != nil { log.Fatal("Error: Couldn't initialize database:", err) return } // Global blog data err = methods.GenerateBlog() if err != nil { log.Fatal("Error: Couldn't generate blog data:", err) return } // Templates err = templates.Generate() if err != nil { log.Fatal("Error: Couldn't compile templates:", err) return } // Plugins err = plugins.Load() if err == nil { // Close LuaPool at the end defer plugins.LuaPool.Shutdown() log.Println("Plugins loaded.") } // HTTP(S) Server httpPort := configuration.Config.HttpHostAndPort httpsPort := configuration.Config.HttpsHostAndPort // Check if HTTP/HTTPS flags were provided if flags.HttpPort != "" { components := strings.SplitAfterN(httpPort, ":", 2) httpPort = components[0] + flags.HttpPort } if flags.HttpsPort != "" { components := strings.SplitAfterN(httpsPort, ":", 2) httpsPort = components[0] + flags.HttpsPort } // Determine the kind of https support (as set in the config.json) switch configuration.Config.HttpsUsage { case "AdminOnly": checkHttpsCertificates() httpRouter := httptreemux.New() httpsRouter := httptreemux.New() // Blog and pages as http server.InitializeBlog(httpRouter) server.InitializePages(httpRouter) // Blog and pages as https server.InitializeBlog(httpsRouter) server.InitializePages(httpsRouter) // Admin as https and http redirect // Add redirection to http router httpRouter.GET("/admin/", httpsRedirect) httpRouter.GET("/admin/*path", httpsRedirect) // Add routes to https router server.InitializeAdmin(httpsRouter) // Start https server log.Println("Starting https server on port " + httpsPort + "...") go func() { err := http.ListenAndServeTLS(httpsPort, filenames.HttpsCertFilename, filenames.HttpsKeyFilename, httpsRouter) if err != nil { log.Fatal("Error: Couldn't start the HTTPS server:", err) } }() // Start http server log.Println("Starting http server on port " + httpPort + "...") err := http.ListenAndServe(httpPort, httpRouter) if err != nil { log.Fatal("Error: Couldn't start the HTTP server:", err) } case "All": checkHttpsCertificates() httpsRouter := httptreemux.New() httpRouter := httptreemux.New() // Blog and pages as https server.InitializeBlog(httpsRouter) server.InitializePages(httpsRouter) // Admin as https server.InitializeAdmin(httpsRouter) // Add redirection to http router httpRouter.GET("/", httpsRedirect) httpRouter.GET("/*path", httpsRedirect) // Start https server log.Println("Starting https server on port " + httpsPort + "...") go func() { err := http.ListenAndServeTLS(httpsPort, filenames.HttpsCertFilename, filenames.HttpsKeyFilename, httpsRouter) if err != nil { log.Fatal("Error: Couldn't start the HTTPS server:", err) } }() // Start http server log.Println("Starting http server on port " + httpPort + "...") err := http.ListenAndServe(httpPort, httpRouter) if err != nil { log.Fatal("Error: Couldn't start the HTTP server:", err) } default: // This is configuration.HttpsUsage == "None" httpRouter := httptreemux.New() // Blog and pages as http server.InitializeBlog(httpRouter) server.InitializePages(httpRouter) // Admin as http server.InitializeAdmin(httpRouter) // Start http server log.Println("Starting server without HTTPS support. Please enable HTTPS in " + filenames.ConfigFilename + " to improve security.") log.Println("Starting http server on port " + httpPort + "...") err := http.ListenAndServe(httpPort, httpRouter) if err != nil { log.Fatal("Error: Couldn't start the HTTP server:", err) } } }
//NewEndPoints creates new prefixed endpoints func NewEndPoints(not *notifier.Notifier, store *sqlstore.Store, convs feeder.Conventions, cfg config.Rest, org config.Internships) EndPoints { ed := EndPoints{ store: store, router: httptreemux.New(), prefix: strings.TrimSuffix(cfg.Prefix, "/"), cfg: cfg, organization: org, conventions: convs, notifier: not, } ed.router.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusNotFound) } //Set the endpoints ed.get("/users/", users) ed.post("/users/", newUser) ed.post("/users/:u/email", setEmail) ed.post("/users/:u/person", setUserPerson) ed.post("/users/:u/role", setUserRole) ed.del("/users/:u", delUser) ed.get("/users/:u", user) ed.del("/users/:u/session", ed.delSession) ed.post("/students/:s/major", setMajor) ed.post("/students/:s/promotion", setPromotion) ed.post("/students/:s/male", setMale) ed.post("/students/:s/alumni", setAlumni) ed.post("/students/:s/skip", setStudentSkippable) ed.get("/students/", students) ed.post("/students/", newStudent) ed.router.GET(ed.prefix+"/internships/", ed.anon(internships)) ed.get("/internships/:s", internship) ed.post("/internships/:s/company", setCompany) ed.post("/internships/:s/supervisor", setSupervisor) ed.post("/internships/:s/tutor", setTutor) ed.del("/internships/:s/defense", rmDefense) ed.post("/internships/:s/defense", setStudentDefense) ed.put("/internships/:s/defense", updateStudentDefense) ed.get("/internships/:s/defense", studentDefense) ed.post("/internships/:s/defense/grade", setDefenseGrade) ed.post("/internships/", ed.newInternship) ed.del("/surveys/:s/:k", resetSurvey) ed.post("/surveys/:s/:k", requestSurvey) ed.get("/reports/:s/:k/", report) ed.get("/reports/:s/:k/content", reportContent) ed.post("/reports/:s/:k/content", setReportContent) ed.post("/reports/:s/:k/deadline", setReportDeadline) ed.post("/reports/:s/:k/grade", setReportGrade) ed.post("/reports/:s/:k/private", setReportPrivacy) ed.get("/conventions/", conventions) ed.get("/conventions/:s", convention) ed.get("/logs/:k", streamLog) ed.get("/logs/", logs) ed.get("/defenses/", defenseSessions) ed.post("/defenses/", newDefenseSession) ed.get("/defenses/:id/:r/", defenseSession) ed.del("/defenses/:id/:r", rmDefenseSession) ed.post("/defenses/:id/:r/jury/", newDefenseSessionJury) ed.del("/defenses/:id/:r/jury/:j", rmDefenseSessionJury) ed.router.GET(ed.prefix+"/program/", ed.anon(ed.program)) ed.router.POST(ed.prefix+"/signin", ed.anon(ed.signin)) ed.router.POST(ed.prefix+"/resetPassword", ed.anon(ed.resetPassword)) ed.router.POST(ed.prefix+"/newPassword", ed.anon(ed.newPassword)) ed.router.GET(ed.prefix+"/config", ed.anon(ed.config)) ed.router.GET(ed.prefix+"/surveys/:t", ed.anon(ed.survey)) ed.router.POST(ed.prefix+"/surveys/:t", ed.anon(ed.setSurvey)) return ed }