func http() { server := martini.Classic() server.Use(martini.Static("public", martini.StaticOptions{ Prefix: "public", })) server.Use(martini.Static("bower_components", martini.StaticOptions{ Prefix: "bower_components", })) server.Use(render.Renderer(render.Options{ Extensions: []string{".tmpl", ".html"}, Delims: render.Delims{"{[{", "}]}"}, })) server.Get("/", func(r render.Render) { r.HTML(200, "index", nil) }) // server.Get("/clients/:pid", func(params martini.Params, r render.Render) { r.HTML(200, "index", params["pid"]) }) type jd map[string]interface{} type ja []interface{} // json api server.Get("/api/clients", func(r render.Render) { client_info := ja{} for _, c := range compositors { var surfaces []Surface for _, s := range c.Surfaces { surfaces = append(surfaces, *s) } client_info = append(client_info, jd{ "pid": c.Pid, "ss": surfaces, }) } r.JSON(200, client_info) }) // websocket api server.Get("/api/clients", websocket.Handler(func(ws *websocket.Conn) { }).ServeHTTP) server.Get("/api/clients/:pid", websocket.Handler(func(ws *websocket.Conn) { }).ServeHTTP) server.Run() }
func main() { m := martini.Classic() StaticOptions := martini.StaticOptions{Prefix: "public"} m.Use(martini.Static("public", StaticOptions)) m.Use(martini.Static("public", StaticOptions)) m.Use(martini.Static("public", StaticOptions)) m.Use(martini.Static("public", StaticOptions)) m.Use(render.Renderer(render.Options{ Directory: "templates", // Specify what path to load the templates from. Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template. Extensions: []string{".tmpl"}, // Specify extensions to load for templates. Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8". })) m.Get("/", IndexRouter) m.Get("/about", AboutRoute) m.Get("/contact", ContactRoute) m.Get("/signin", SigninRoute) m.Get("/signup", SignupRoute) m.Run() }
func (web *MailWeb) initHandlers() { // Public Handlers web.martini.Get("/", web.welcome) web.martini.Post("/", binding.Bind(auth.WatneyUser{}), web.authenticate) // Reserved for martini sessionauth forwarding, in case the session timed out web.martini.Get("/sessionTimeout", web.timeout) // Private Handlers web.martini.Get("/logout", sessionauth.LoginRequired, web.logout) web.martini.Get("/main", sessionauth.LoginRequired, web.main) web.martini.Post("/mailContent", sessionauth.LoginRequired, web.mailContent) web.martini.Post("/mails", sessionauth.LoginRequired, web.mails) web.martini.Post("/poll", sessionauth.LoginRequired, web.poll) web.martini.Post("/sendMail", sessionauth.LoginRequired, web.sendMail) web.martini.Post("/moveMail", sessionauth.LoginRequired, web.moveMail) web.martini.Post("/trashMail", sessionauth.LoginRequired, web.trashMail) web.martini.Post("/updateFlags", sessionauth.LoginRequired, web.updateFlags) web.martini.Post("/userInfo", sessionauth.LoginRequired, web.userInfo) // Static content web.martini.Use(martini.Static("static/resources/libs/", martini.StaticOptions{Prefix: "/libs/"})) web.martini.Use(martini.Static("static/resources/js/", martini.StaticOptions{Prefix: "/js/"})) web.martini.Use(martini.Static("static/resources/css/", martini.StaticOptions{Prefix: "/css/"})) }
// ListenAndServe start the server func ListenAndServe(addr string, core core.Core, fe fs.FileExplorer) { log.Infof("REST listening at: http://%v", core.GetAddr()) clientHandlers := clientAPI.NewHandler(core) mesosHandlers := mesosAPI.NewHandler(core) fsHandlers := fsAPI.NewHandler(fe) r := createRouter(core, clientHandlers, mesosHandlers, fsHandlers) m := martini.New() m.Use(cors.Allow(&cors.Options{ AllowOrigins: []string{"*"}, AllowMethods: []string{"POST", "GET", "PUT", "DELETE"}, AllowHeaders: []string{"Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: false, })) m.Use(logger()) m.Use(recovery()) m.Use(martini.Static("static")) m.Use(martini.Static("temp", martini.StaticOptions{ Prefix: "/context/", })) m.Use(martini.Static("executor", martini.StaticOptions{ Prefix: "/executor/", })) m.Action(r.Handle) go m.RunOnAddr(addr) }
func main() { martini.Env = martini.Prod m := martini.Classic() m.Use(martini.Static("../../admin/static/")) m.Use(martini.Static(APP_STORE_DIR)) m.Use(sessions.Sessions("compass_session", sessions.NewCookieStore([]byte("compass_session_cookie")))) m.Get("/", func(w http.ResponseWriter) string { w.Header().Set("content-type", "text/html") return SCRIPT_LOGIN }) m.Get("/checkcode", func(r *http.Request, w http.ResponseWriter, s sessions.Session) { code := captcha.NewLen(4) s.Set("checkcode", code) captcha.WriteImage(w, code, 110, 40) }) showTemplate([]string{"footer", "form", "index", "left", "login", "main", "right", "top"}, m) for actionName, actionHandler := range admin.ActionHandlers { m.Post(fmt.Sprintf("/action/%s", actionName), actionHandler) } m.RunOnAddr(SERVER_ADDR) }
func configureAssets(m *mart.ClassicMartini, analyticsConfig AnalyticsConfig, logger boshlog.Logger) { assetsIDBytes, err := ioutil.ReadFile("./public/assets-id") ensureNoErr(logger, "Failed to find assets ID", err) assetsID := strings.TrimSpace(string(assetsIDBytes)) assetsFuncs := template.FuncMap{ "cssPath": func(fileName string) (string, error) { return "/" + assetsID + "/stylesheets/" + fileName, nil }, "jsPath": func(fileName string) (string, error) { return "/" + assetsID + "/javascript/" + fileName, nil }, "imgPath": func(fileName string) (string, error) { return "/" + assetsID + "/images/" + fileName, nil }, } analyticsConfigFuncs := template.FuncMap{ "analyticsConfig": func() AnalyticsConfig { return analyticsConfig }, } htmlFuncs := template.FuncMap{ "href": func(s string) template.HTMLAttr { return template.HTMLAttr(fmt.Sprintf(" href='%s' ", s)) }, } // Use prefix to cache bust images, stylesheets, and js m.Use(mart.Static( "./public", mart.StaticOptions{ Prefix: assetsID, }, )) // Make sure docs' images are available as `docs/images/X` m.Use(mart.Static( "./templates/docs/images", mart.StaticOptions{ Prefix: "docs/images", }, )) m.Use(martrend.Renderer( martrend.Options{ Layout: "layout", Directory: "./templates", Extensions: []string{".tmpl", ".html"}, Funcs: []template.FuncMap{assetsFuncs, analyticsConfigFuncs, htmlFuncs}, }, )) }
func main() { arguments := os.Args[1:] port := arguments[0] server := martini.Classic() server.Use(martini.Static("../public")) server.Use(martini.Static("../assets/javascript/app")) server.Use(nocache.UpdateCacheHeaders()) fmt.Printf(" listening on port %s\n", port) log.Fatal(http.ListenAndServe(":"+port, server)) }
func configureServer(server *martini.Martini, router martini.Router) { server.Use(martini.Recovery()) server.Use(middleware.Logger()) server.Use(martini.Static("templates/public", martini.StaticOptions{SkipLogging: true})) server.Use(martini.Static("templates/images", martini.StaticOptions{Prefix: "images", SkipLogging: true})) server.Use(martini.Static("templates/styles", martini.StaticOptions{Prefix: "styles", SkipLogging: true})) server.Use(martini.Static("templates/scripts", martini.StaticOptions{Prefix: "scripts", SkipLogging: true})) server.Use(render.Renderer(render.Options{ Layout: "layout", })) server.MapTo(router, (*martini.Routes)(nil)) server.Action(router.Handle) }
func Configure(m *martini.ClassicMartini) { m.Group("/humidity", func(r martini.Router) { r.Post("", humidity.Post) r.Get("", humidity.Get) }) m.Get("/current/humidity", current_humidity.Get) m.Group("/", func(r martini.Router) { r.Get("", index.Get) }) static := martini.Static("templates", martini.StaticOptions{Fallback: "/index.tmpl", Exclude: "/api/v"}) m.NotFound(static, http.NotFound) m.Use(martini.Static("static")) }
func main() { m := martini.Classic() conf := config.LoadConf(martini.Env) //create new session middleware store := sessions.NewCookieStore([]byte("MushareSecret")) store.Options(sessions.Options{ Path: "/", Domain: conf.App.Host, MaxAge: 60 * 60 * 60 * 24, HttpOnly: true, }) //middleware m.Handlers( middlewares.LogOutput, middlewares.Recovery(), martini.Logger(), sessions.Sessions("_session", store), martini.Static("static", martini.StaticOptions{}), middlewares.InjectRedis(), middlewares.InjectDB(), ) m.Map(conf) //routers router.Include(m) //start server m.RunOnAddr(conf.App.Host + ":" + conf.App.Port) }
func init() { m = martini.New() // I could probably just use martini.Classic() instead of configure these manually // Static files m.Use(martini.Static(`public`)) // Setup middleware m.Use(martini.Recovery()) m.Use(martini.Logger()) // m.Use(auth.Basic(AuthToken, "")) m.Use(MapEncoder) // Setup routes r := martini.NewRouter() r.Get(`/albums`, server.GetAlbums) r.Get(`/albums/:id`, server.GetAlbum) r.Post(`/albums`, server.AddAlbum) r.Put(`/albums/:id`, server.UpdateAlbum) r.Delete(`/albums/:id`, server.DeleteAlbum) // Inject database m.MapTo(server.DBInstance, (*server.DB)(nil)) // Add the router action m.Action(r.Handle) }
func main() { m := martini.Classic() store := sessions.NewCookieStore([]byte("secret-isucon")) m.Use(sessions.Sessions("isucon_go_session", store)) m.Use(martini.Static("../public")) m.Use(render.Renderer(render.Options{ Layout: "layout", })) m.Get("/", func(r render.Render, session sessions.Session) { r.HTML(200, "index", map[string]string{"Flash": getFlash(session, "notice")}) }) m.Post("/login", func(req *http.Request, r render.Render, session sessions.Session) { user, err := attemptLogin(req) notice := "" if err != nil || user == nil { switch err { case ErrBannedIP: notice = "You're banned." case ErrLockedUser: notice = "This account is locked." default: notice = "Wrong username or password" } session.Set("notice", notice) r.Redirect("/") return } session.Set("user_id", strconv.Itoa(user.ID)) r.Redirect("/mypage") }) m.Get("/mypage", func(r render.Render, session sessions.Session) { currentUser := getCurrentUser(session.Get("user_id")) if currentUser == nil { session.Set("notice", "You must be logged in") r.Redirect("/") return } currentUser.getLastLogin() r.HTML(200, "mypage", currentUser) }) m.Get("/report", func(r render.Render) { r.JSON(200, map[string][]string{ "banned_ips": bannedIPs(), "locked_users": lockedUsers(), }) }) http.ListenAndServe(":8080", m) }
func main() { m := martini.Classic() op := martini.StaticOptions{Prefix: "/", SkipLogging: true, IndexFile: "", Expires: func() string { return "" }} m.Use(martini.Static(".", op)) m.RunOnAddr(":4000") }
//初始化并启动web服务 func StartManager(sl *schedule.ScheduleManager) { // {{{ g = sl.Global m := martini.Classic() m.Use(Logger) m.Use(martini.Static("web/public")) m.Use(web.ContextWithCookieSecret("")) m.Use(render.Renderer(render.Options{ Directory: "web/templates", // Specify what path to load the templates from. Extensions: []string{".tmpl", ".html"}, // Specify extensions to load for templates. Delims: render.Delims{"{[{", "}]}"}, Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8". IndentJSON: true, // Output human readable JSON IndentXML: true, // Output human readable XML HTMLContentType: "text/html", // Output XHTML content type instead of default "text/html" })) m.Map(sl) controller(m) g.L.Println("Web manager is running in ", g.ManagerPort) err := http.ListenAndServe(g.ManagerPort, m) if err != nil { log.Fatal("Fail to start server: %v", err) } } // }}}
func main() { fmt.Println("jøkulhlaup ", Version) r := render.New(render.Options{}) m := martini.Classic() fizz := fizz.New() // Dashboard m.Get("/", func(w http.ResponseWriter, req *http.Request) { data := map[string]string{ "title": "Jøkulhlaup", "imgsrc": "img/jøkulhlaup.png", "width": "1440", "height": "900", } // !! Reload template !! //r = render.New(render.Options{}) // Render the specified templates/.tmpl file as HTML and return r.HTML(w, http.StatusOK, "black", data) }) // Activate the permission middleware m.Use(fizz.All()) // Share the files in static m.Use(martini.Static("static")) m.Run() // port 3000 by default }
func NewRouter(c *container.ContainerBag) *martini.ClassicMartini { var ( indexHandler = handler.NewIndexHandler(c) buildersHandler = handler.NewBuildersHandler(c) wsHandler = handler.NewWsHandler(c) ) router := martini.Classic() router.Use(martini.Static("static/assets")) router.Use(render.Renderer(render.Options{ Directory: "static/templates", Layout: "layout", Extensions: []string{".tmpl", ".html"}, Charset: "UTF-8", IndentJSON: true, Funcs: []template.FuncMap{ { "genericSize": func() string { return c.GenericSize }, }, }, })) router.Get("/", indexHandler.ServeHTTP) router.Get("/ws", wsHandler.ServeHTTP) router.Get("/builders", buildersHandler.ServeHTTP) return router }
func main() { m := martini.Classic() m.Use(render.Renderer(render.Options{ Directory: "templates", Layout: "layout", Extensions: []string{".html"}, Delims: render.Delims{"{[{", "}]}"}, Funcs: []template.FuncMap{ { "formatTime": func(args ...interface{}) string { t1 := time.Unix(args[0].(int64), 0) return t1.Format(time.Stamp) }, "unescaped": func(args ...interface{}) template.HTML { return template.HTML(args[0].(string)) }, }, }, })) newmap := map[string]interface{}{} m.Use(martini.Static("assets")) m.Get("/", func(args martini.Params, r render.Render) string { r.HTML(200, "index", newmap) return "" }) m.Run() }
func main() { //go ServeWebsocket() m := martini.Classic() m.Use(render.Renderer(render.Options{ Layout: "layout", })) m.Use(martini.Static("assets")) m.Get("/", func(r render.Render) { r.HTML(200, "index", "index") }) // api group m.Group("/api", func(r martini.Router) { r.Post("/log", binding.Bind(Log{}), NewLog) r.Get("/log/:appname", func(args martini.Params, r render.Render) { logs, err := GetLogForApp(args["appname"]) if err != nil { r.JSON(200, map[string]interface{}{}) } r.JSON(200, logs) }) }) //websocket m.Get("/sock/:appname", socketHandler) m.Run() }
func Start() { m := martini.Classic() m.Get("/", indexHandler) m.Get("/choose/:word", chooseHandler) m.Get("/movie/:title", movieHandler) m.Get("/keyword/:word", keywordHandler) m.Get("/search/movie/", movieSearchHandler) m.Get("/search_results/movie/:search", searchResultsHandler) m.Use(martini.Static(filepath.Join(frontEndRoot, "js"))) m.Use(martini.Static(filepath.Join(frontEndRoot, "css"))) m.Run() }
func launchFrontend() { m := martini.New() m.Use(martini.Static("static")) m.Use(martini.Recovery()) m.Use(martini.Logger()) r := martini.NewRouter() r.Get("/", indexHandler) r.Get("/following", followHandler) r.Get("/stat", statHandler) r.Get("/channel/:streamer", channelHandler) r.Get("/add/:streamer", addHandler) r.Get("/del/:streamer", delHandler) r.Get("/api/stat/:streamer", apiStat) r.Get("/api/channel/:streamer", apiStat) r.Get("/api/following", apiFollowing) db := getDB() redis := getRedis() m.Map(db) m.Map(redis) m.Action(r.Handle) log.Print("Started Web Server") m.Run() }
// standardHttp starts serving standard HTTP (api/web) requests, to be used by normal clients func standardHttp(discovery bool) { m := martini.Classic() if config.Config.HTTPAuthUser != "" { m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword)) } // Render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "resources", Layout: "templates/layout", HTMLContentType: "text/html", })) m.Use(martini.Static("resources/public")) log.Info("Starting HTTP") if discovery { go orchestrator.ContinuousDiscovery() } http.API.RegisterRequests(m) http.Web.RegisterRequests(m) // Serve m.Run() }
// Entry point for running the application. // It defines all routes and middleware used // and starts the underlying server. func Start() { // Set up our Martini instance m := martini.Classic() // Middleware // m.Use(gzip.All()) m.Use(render.Renderer()) // Routes m.Group("/admin", func(r martini.Router) { a := handlers.Admin{} r.Get("", a.Index) r.Get("/posts", a.Posts.Index) r.Get("/posts/new", a.Posts.New) r.Get("/posts/:id/edit", a.Posts.Edit) }, render.Renderer(render.Options{ Layout: "admin/layout", })) m.Group("/api", func(r martini.Router) { a := handlers.Api{} r.Get("", a.Index) r.Get("/posts", a.Posts.Index) r.Post("/posts", a.Posts.Create) r.Get("/posts/:id", a.Posts.Show) r.Get("/render/markdown", a.Render.Markdown) }) // Serve from static if possible m.Use(martini.Static(util.Config().App.SiteDir)) m.Run() }
func GetNewTestRouter(cfg *config.Config, buildbot bb.Buildbot) *martini.ClassicMartini { m := martini.Classic() m.Use(martini.Static("../static/assets")) m.Use(render.Renderer(render.Options{ Directory: "../static/templates", Layout: "layout", Extensions: []string{".tmpl", ".html"}, Charset: "UTF-8", IndentJSON: true, Funcs: []template.FuncMap{ { "refreshSec": func() string { return strconv.Itoa(cfg.RefreshSec) }, "buildbotUrl": func() string { return buildbot.GetUrl() }, "hashedUrl": func() string { return cfg.HashedUrl }, }, }, })) return m }
// Http starts serving HTTP (api/web) requests func Http() { martini.Env = martini.Prod m := martini.Classic() if config.Config.HTTPAuthUser != "" { m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword)) } m.Use(gzip.All()) // Render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "resources", Layout: "templates/layout", HTMLContentType: "text/html", })) m.Use(martini.Static("resources/public")) go agent.ContinuousOperation() log.Infof("Starting HTTP on port %d", config.Config.HTTPPort) http.API.RegisterRequests(m) // Serve if config.Config.UseSSL { log.Info("Serving via SSL") err := nethttp.ListenAndServeTLS(fmt.Sprintf(":%d", config.Config.HTTPPort), config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, m) if err != nil { log.Fatale(err) } } else { nethttp.ListenAndServe(fmt.Sprintf(":%d", config.Config.HTTPPort), m) } }
func mount(war string) { m := martini.Classic() m.Handlers(martini.Recovery()) m.Use(gzip.All()) m.Use(martini.Static(war, martini.StaticOptions{SkipLogging: true})) // m.Use(render.Renderer(render.Options{ // Extensions: []string{".html", ".shtml"}, // })) // m.Use(render.Renderer()) // m.Use(midTextDefault) //map web m.Use(func(w http.ResponseWriter, c martini.Context) { web := &Web{w: w} c.Map(web) }) m.Group("/test", func(api martini.Router) { api.Get("", mainHandler) api.Get("/1", test1Handler) api.Get("/2", test2Handler) }) http.Handle("/", m) }
//InitRoutes - initialize the mappings for controllers against valid routes func InitRoutes(m *martini.ClassicMartini, redisConn Doer, mongoConn pezdispenser.MongoCollectionGetter, authClient AuthRequestCreator) { setOauthConfig() keyGen := NewKeyGen(redisConn, &GUIDMake{}) m.Use(render.Renderer()) m.Use(martini.Static(StaticPath)) m.Use(oauth2.Google(OauthConfig)) authKey := NewAuthKeyV1(keyGen) m.Get("/info", authKey.Get()) m.Get(ValidKeyCheck, NewValidateV1(keyGen).Get()) m.Get("/me", oauth2.LoginRequired, DomainCheck, NewMeController().Get()) m.Get("/", oauth2.LoginRequired, DomainCheck, func(params martini.Params, log *log.Logger, r render.Render, tokens oauth2.Tokens) { userInfo := GetUserInfo(tokens) r.HTML(SuccessStatus, "index", userInfo) }) m.Post("/sandbox", oauth2.LoginRequired, DomainCheck, NewSandBoxController().Post()) m.Group(URLAuthBaseV1, func(r martini.Router) { r.Put(APIKey, authKey.Put()) r.Get(APIKey, authKey.Get()) r.Delete(APIKey, authKey.Delete()) }, oauth2.LoginRequired, DomainCheck) m.Group(URLOrgBaseV1, func(r martini.Router) { pcfOrg := NewOrgController(mongoConn, authClient) r.Put(OrgUser, pcfOrg.Put()) r.Get(OrgUser, pcfOrg.Get()) }, oauth2.LoginRequired, DomainCheck) }
func Start(port string, onStart func()) { // Logging init flag.Set("log_dir", utils.GetRuntimeDir(config.GetString("log_dir"))) flag.Set("alsologtostderr", "true") flag.Parse() defer glog.Flush() m := martini.Classic() m.Use(render.Renderer(render.Options{ Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8". Delims: render.Delims{"${", "}"}, Directory: utils.GetRuntimeDir("resources/views"), })) m.Use(martini.Static(utils.GetRuntimeDir("public"))) controller.MappingController(m) http.Handle("/rpc", rpc.GetServer()) http.Handle("/", m) if db.IsConnected() { defer db.Close() } onStart() for _, fn := range methods { go fn() } http.ListenAndServe(":"+port, nil) }
func main() { app := martini.Classic() app.Use(db.DB()) app.Use(martini.Static("public")) app.Use(render.Renderer(render.Options{ Directory: "views", Layout: "layout", Extensions: []string{".html"}, })) app.Get("/", handlers.IndexHandler) app.Group("/api", func(route martini.Router) { route.Get("/info", handlers.GetInfoHandler) route.Get("/items", handlers.GetItemsHandler) route.Get("/items/:id", handlers.GetItemHandler) route.Post("/items", binding.Json(types.Item{}), handlers.PostItemHandler) route.Delete("/items/:id", handlers.DeleteItemHandler) route.Put("/items/:id", binding.Json(types.Item{}), handlers.UpdateItemHandler) }) http.ListenAndServe(config.Get("dev").Port, app) }
func main() { autoUpdate() m := martini.Classic() m.Use(martini.Static("static")) m.Use(render.Renderer()) m.Get("/", func(r render.Render) { r.HTML(200, "content", []interface{}{getPage(1)}) }) m.Get("/api/:id", func(params martini.Params, r render.Render) { s := strings.Trim(params["id"], " .)(") id := atoi(s) r.JSON(200, getPage(id)) }) m.Get("/page/:id", func(params martini.Params, r render.Render) { s := strings.Trim(params["id"], " .)(") id := atoi(s) r.HTML(200, "content", []interface{}{getPage(id)}) }) http.ListenAndServe("0.0.0.0:8000", m) m.Run() }
func main() { m := martini.Classic() m.Get("/sources/:sourceId/stats", func(res http.ResponseWriter, params martini.Params) { // TODO: Read from database var err error enc := json.NewEncoder(res) switch params["sourceId"] { case "1": err = enc.Encode(testSources[0].Stats) case "2": err = enc.Encode(testSources[1].Stats) default: panic("Source doesn't exist!") } if err != nil { panic(err) } }) m.Get("/sources", func(res http.ResponseWriter, req *http.Request) { // TODO: Read from database err := json.NewEncoder(res).Encode(testSources) if err != nil { panic(err) } }) m.Use(martini.Static("static")) log.Fatal(http.ListenAndServe(":8080", m)) }