func Start() { r := martini.NewRouter() m := martini.New() m.Use(martini.Logger()) m.Use(martini.Recovery()) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) // Gitchain API r.Post("/rpc", jsonRpcService().ServeHTTP) r.Get("/info", info) // Git Server r.Post("^(?P<path>.*)/git-upload-pack$", func(params martini.Params, req *http.Request) string { body, _ := ioutil.ReadAll(req.Body) fmt.Println(req, body) return params["path"] }) r.Post("^(?P<path>.*)/git-receive-pack$", func(params martini.Params, req *http.Request) string { fmt.Println(req) return params["path"] }) r.Get("^(?P<path>.*)/info/refs$", func(params martini.Params, req *http.Request) (int, string) { body, _ := ioutil.ReadAll(req.Body) fmt.Println(req, body) return 404, params["path"] }) log.Fatal(http.ListenAndServe(fmt.Sprintf("127.0.0.1:%d", env.Port), m)) }
func main() { conf.Env().Flag() r := martini.NewRouter() m := martini.New() if conf.UBool("debug") { m.Use(martini.Logger()) } m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) session, err := mgo.Dial(conf.UString("mongo.uri")) if err != nil { panic(err) } session.SetMode(mgo.Monotonic, true) db := session.DB(conf.UString("mongodb.database")) logger := log.New(os.Stdout, "\x1B[36m[cdn] >>\x1B[39m ", 0) m.Map(logger) m.Map(db) r.Group("", cdn.Cdn(cdn.Config{ MaxSize: conf.UInt("maxSize"), ShowInfo: conf.UBool("showInfo"), TailOnly: conf.UBool("tailOnly"), })) logger.Println("Server started at :" + conf.UString("port", "5000")) _err := http.ListenAndServe(":"+conf.UString("port", "5000"), m) if _err != nil { logger.Printf("\x1B[31mServer exit with error: %s\x1B[39m\n", _err) os.Exit(1) } }
// Route return the route handler for this func (s ServiceRegistryWebService) Route() martini.Router { r := martini.NewRouter() r.Group("/apiversions/", func(r martini.Router) { r.Get("", s.getAPIVersions) r.Post("", binding.Bind(common.APIVersion{}), s.createAPIVersion) }) r.Group("/apiversions/:version/", func(r martini.Router) { r.Get("", s.getAPIVersion) r.Get("services/", s.getAPIServices) r.Post("services/", binding.Bind(common.ServiceVersion{}), s.createAPIService) }) r.Group("/services/", func(r martini.Router) { r.Get("", s.getServices) r.Post("", binding.Bind(common.ServiceDefinition{}), s.createService) r.Delete(":service/", s.dropService) }) r.Group("/services/:service/versions", func(r martini.Router) { r.Get("", s.getServiceVersions) r.Post("", binding.Bind(common.ServiceVersion{}), s.createServiceVersion) }) r.Group("/services/:service/:version/hosts/", func(r martini.Router) { r.Get("", s.getServiceHosts) r.Post("", binding.Bind(common.ServiceHost{}), s.attachServiceHost) }) return r }
func formTestMartini() *martini.Martini { config := configuration.ReadTestConfigInRecursive() mainDb := db.NewMainDb(config.Main.Database.ConnString, config.Main.Database.Name) m := web.NewSessionAuthorisationHandler(mainDb) m.Use(render.Renderer(render.Options{ Directory: "templates/auth", Extensions: []string{".tmpl", ".html"}, Charset: "UTF-8", })) router := martini.NewRouter() router.Get("/", func(r render.Render) { r.HTML(200, "login", nil) }) router.Group("/test", func(r martini.Router) { r.Get("/:id", func(ren render.Render, prms martini.Params) { id := prms["id"] ren.JSON(200, map[string]interface{}{"id": id}) }) r.Get("/new", func(ren render.Render) { ren.JSON(200, nil) }) r.Get("/update/:id", func(ren render.Render, prms martini.Params) { id := prms["id"] ren.JSON(200, map[string]interface{}{"id": id}) }) r.Get("/delete/:id", func(ren render.Render, prms martini.Params) { id := prms["id"] ren.JSON(200, map[string]interface{}{"id": id}) }) }) m.Action(router.Handle) return m }
func Test_todoapp_500(t *testing.T) { m := setupMartini() r := martini.NewRouter() m.Action(r.Handle) hostname := currentHostname defer func() { currentHostname = hostname }() currentHostname = "will_cause_error" r.Get("/api/ip", DataHandler("ip")) response := httptest.NewRecorder() req, err := http.NewRequest("GET", "http://localhost:4005/api/ip", nil) if err != nil { t.Fatal(err) } m.ServeHTTP(response, req) Expect(t, response.Code, http.StatusInternalServerError) body := response.Body.String() Contain(t, body, `<h1>500 - Internal Server Error</h1>`) Contain(t, body, `<h4>lookup will_cause_error: no such host</h4>`) }
// How to use Martini properly with Defer Panic client library func main() { dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c") go dps.CaptureStats() m := martini.New() r := martini.NewRouter() r.Get("/panic", func() string { panic("There is no need for panic") return "Hello world!" }) r.Get("/slow", func() string { time.Sleep(5 * time.Second) return "Hello world!" }) r.Get("/fast", func() string { return "Hello world!" }) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) m.Use(middleware.Wrapper(dps)) m.RunOnAddr(":3000") }
func StartWeb() { m := martini.Classic() store := sessions.NewCookieStore([]byte("mandela")) m.Use(sessions.Sessions("session", store)) m.Use(render.Renderer(render.Options{ Extensions: []string{".html"}, })) m.Use(martini.Static("../../statics")) r := martini.NewRouter() r.Get("/", Home_handler) //首页 r.Get("/getdomain", GetDomain_handler) //获得本机的域名 m.Action(r.Handle) webPort := 80 for i := 0; i < 1000; i++ { _, err := net.ListenPacket("udp", ":"+strconv.Itoa(webPort)) if err != nil { webPort = webPort + 1 } else { break } } m.RunOnAddr(":" + strconv.Itoa(webPort)) 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() }
func init() { m = martini.New() //set up middleware m.Use(martini.Recovery()) m.Use(martini.Logger()) m.Use(auth.Basic(AuthToken, "")) m.Use(MapEncoder) // set up routes r := martini.NewRouter() r.Get(`/albums`, GetAlbums) r.Get(`/albums/:id`, GetAlbum) r.Post(`/albums`, AddAlbum) r.Put(`/albums/:id`, UpdateAlbum) r.Delete(`/albums/:id`, DeleteAlbum) // inject database // maps db package variable to the DB interface defined in data.go // The syntax for the second parameter may seem weird, // it is just converting nil to the pointer-to-DB-interface type, // because all the injector needs is the type to map the first parameter to. m.MapTo(db, (*DB)(nil)) // add route action // adds the router’s configuration to the list of handlers that Martini will call. m.Action(r.Handle) }
func setupMultiple(mockEndpoints []MockRoute) { mux = http.NewServeMux() server = httptest.NewServer(mux) fakeUAAServer = FakeUAAServer() m := martini.New() m.Use(render.Renderer()) r := martini.NewRouter() for _, mock := range mockEndpoints { method := mock.Method endpoint := mock.Endpoint output := mock.Output if method == "GET" { r.Get(endpoint, func() string { return output }) } else if method == "POST" { r.Post(endpoint, func() string { return output }) } } r.Get("/v2/info", func(r render.Render) { r.JSON(200, map[string]interface{}{ "authorization_endpoint": fakeUAAServer.URL, "token_endpoint": fakeUAAServer.URL, "logging_endpoint": server.URL, }) }) m.Action(r.Handle) mux.Handle("/", m) }
// Create the router. func createRouter() martini.Router { router := martini.NewRouter() router.Get("/api/feed/list", api.FeedList()) router.Get("/api/feed/subscription", api.IsSubscribed()) router.Post("/api/feed/subscription", api.Subscribe()) router.Post("/api/feed/id/:id", api.Update()) router.Get("/api/feed/id/:id", api.FeedInfo()) router.Put("/api/feed/id/:id", api.UpdateFeedAndTags()) router.Delete("/api/feed/id/:id", api.DeleteFeed()) router.Get("/api/articles/random", api.RandomArticleList()) router.Get("/api/articles/unread/:limit/:offset", api.ArticleList("unread")) router.Get("/api/articles/fid/:fid/:limit/:offset", api.ArticleList("fid")) router.Get("/api/articles/tag/:tag/:limit/:offset", api.ArticleList("tag")) router.Get("/api/articles/starred/:limit/:offset", api.ArticleList("starred")) router.Get("/api/articles/search/:deflimit", api.SearchList()) router.Put("/api/articles/read", api.MarkArticlesRead()) router.Put("/api/articles/starred", api.MarkArticlesStarred()) router.Get("/api/article/content/:id", api.Article()) router.Put("/api/article/read/:id", api.MarkReadStatus(true)) // mark read router.Put("/api/article/unread/:id", api.MarkReadStatus(false)) // mark unread router.Get("/api/tags/list", api.TagsList()) router.Get("/api/system/settings", api.Settings()) router.Put("/api/system/shutdown", api.CloseServer()) router.Get("/api/", api.Status()) // do not need api token router.Get("/api/checktoken", api.Status()) // check api token router.Any("/api/**", api.Default()) return router }
func BenchmarkCodegangstaNegroni_Composite(b *testing.B) { namespaces, resources, requests := resourceSetup(10) martiniMiddleware := func(rw http.ResponseWriter, r *http.Request, c martini.Context) { c.Next() } handler := func(rw http.ResponseWriter, r *http.Request, c *martiniContext) { fmt.Fprintf(rw, c.MyField) } r := martini.NewRouter() m := martini.New() m.Use(func(rw http.ResponseWriter, r *http.Request, c martini.Context) { c.Map(&martiniContext{MyField: r.URL.Path}) c.Next() }) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Action(r.Handle) for _, ns := range namespaces { for _, res := range resources { r.Get("/"+ns+"/"+res, handler) r.Post("/"+ns+"/"+res, handler) r.Get("/"+ns+"/"+res+"/:id", handler) r.Put("/"+ns+"/"+res+"/:id", handler) r.Delete("/"+ns+"/"+res+"/:id", handler) } } benchmarkRoutes(b, m, requests) }
func startMartini() { mux := martini.NewRouter() mux.Get("/hello", martiniHandlerWrite) martini := martini.New() martini.Action(mux.Handle) http.ListenAndServe(":"+strconv.Itoa(port), martini) }
func main() { username, password := waitForPostgres(serviceName) db, err := postgres.Open(serviceName, fmt.Sprintf("dbname=postgres user=%s password=%s", username, password)) if err != nil { log.Fatal(err) } r := martini.NewRouter() m := martini.New() m.Use(martini.Logger()) m.Use(martini.Recovery()) m.Use(render.Renderer()) m.Action(r.Handle) m.Map(db) r.Post("/databases", createDatabase) r.Get("/ping", ping) port := os.Getenv("PORT") if port == "" { port = "3000" } addr := ":" + port if err := discoverd.Register(serviceName+"-api", addr); err != nil { log.Fatal(err) } log.Fatal(http.ListenAndServe(addr, m)) }
func BenchmarkCodegangstaMartini_Middleware(b *testing.B) { martiniMiddleware := func(rw http.ResponseWriter, r *http.Request, c martini.Context) { c.Next() } r := martini.NewRouter() m := martini.New() m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Use(martiniMiddleware) m.Action(r.Handle) r.Get("/action", helloHandler) rw, req := testRequest("GET", "/action") b.ResetTimer() for i := 0; i < b.N; i++ { m.ServeHTTP(rw, req) if rw.Code != 200 { panic("no good") } } }
func main() { db, err := bolt.Open("mpush.db", 0666, nil) if err != nil { log.Fatal(err) } defer db.Close() m := martini.Classic() m.Use(render.Renderer()) // Setup routes r := martini.NewRouter() r.Get(`/api/v0/lists`, allLists) r.Get(`/api/v0/lists/:id`, findList) r.Post(`/api/v0/lists`, createList) r.Put(`/api/v0/lists/:id`, updateList) r.Delete(`/api/v0/lists/:id`, removeList) r.Post("/api/v0/push", pushHandler) // Inject database m.Map(db) // Add the router action m.Action(r.Handle) m.Run() }
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 createRoutes() { router = martini.NewRouter() router.Get("/proberequests", GetAllProbeRequests) router.Get("/count", GetProbeRequestCount) m.MapTo(router, (*martini.Routes)(nil)) m.Action(router.Handle) }
func (server *Server) resetRouter() { router := martini.NewRouter() server.martini.Router = router server.martini.MapTo(router, (*martini.Routes)(nil)) server.martini.Action(router.Handle) server.addOptionsRoute() }
/* Application entry point */ func main() { m := martini.New() //Set middleware m.Use(martini.Recovery()) m.Use(martini.Logger()) m.Use(cors.Allow(&cors.Options{ AllowOrigins: []string{"*"}, AllowMethods: []string{"OPTIONS", "HEAD", "POST", "GET", "PUT"}, AllowHeaders: []string{"Authorization", "Content-Type"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, })) //Create the router r := martini.NewRouter() //Options matches all and sends okay r.Options(".*", func() (int, string) { return 200, "ok" }) api.SetupTodoRoutes(r) api.SetupCommentRoutes(r) mscore.StartServer(m, r) fmt.Println("Started NSQ Test service") }
func withoutLogging() *myClassic { r := martini.NewRouter() m := martini.New() m.Use(martini.Recovery()) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return &myClassic{m, r} }
func main() { m := martini.New() m.Use(martini.Logger()) m.Use(martini.Recovery()) m.Use(martini.Static("public")) r := martini.NewRouter() m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) // Instantiate OAuthService with the OAuth App Client Id & Secret from the Environment Variables o, err := coinbase.OAuthService(os.Getenv("COINBASE_CLIENT_ID"), os.Getenv("COINBASE_CLIENT_SECRET"), "https://localhost:8443/tokens") if err != nil { panic(err) return } // At https://localhost:8443/ we will display an "authorize" link r.Get("/", func() string { authorizeUrl := o.CreateAuthorizeUrl([]string{ "user", "balance", }) link := "<a href='" + authorizeUrl + "'>authorize</a>" return link }) // AuthorizeUrl redirects to https://localhost:8443/tokens with 'code' in its // query params. If you dont have SSL enabled, replace 'https' with 'http' // and reload the page. If successful, the user's balance will show r.Get("/tokens", func(res http.ResponseWriter, req *http.Request) string { // Get the tokens given the 'code' query param tokens, err := o.NewTokensFromRequest(req) // Will use 'code' query param from req if err != nil { return err.Error() } // instantiate the OAuthClient c := coinbase.OAuthClient(tokens) amount, err := c.GetBalance() if err != nil { return err.Error() } return strconv.FormatFloat(amount, 'f', 6, 64) }) // HTTP go func() { if err := http.ListenAndServe(":8080", m); err != nil { log.Fatal(err) } }() // HTTPS // To generate a development cert and key, run the following from your *nix terminal: // go run $(go env GOROOT)/src/pkg/crypto/tls/generate_cert.go --host="localhost" if err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", m); err != nil { log.Fatal(err) } }
func newMartini() *martini.ClassicMartini { r := martini.NewRouter() m := martini.New() m.Use(martini.Logger()) m.Use(martini.Recovery()) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return &martini.ClassicMartini{m, r} }
func NewMartini() *martini.ClassicMartini { r := martini.NewRouter() m := martini.New() m.Use(martini.Recovery()) m.Use(render.Renderer()) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return &martini.ClassicMartini{Martini: m, Router: r} }
func nolog() *martini.ClassicMartini { r := martini.NewRouter() m := martini.New() m.Use(martini.Recovery()) m.Use(martini.Static("public")) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return &martini.ClassicMartini{m, r} }
func setupServer() *martini.ClassicMartini { router := martini.NewRouter() server := martini.New() server.Use(martini.Recovery()) server.Use(requestLogger) server.MapTo(router, (*martini.Routes)(nil)) server.Action(router.Handle) return &martini.ClassicMartini{server, router} }
func Routes(m *martini.Martini) { r := martini.NewRouter() r.Get(`/`, controllers.Index) r.Get(`/hello`, middlewares.ApiVerify(), controllers.Hello) // Add the router action m.Action(r.Handle) }
func newMartini() *martini.ClassicMartini { r := martini.NewRouter() m := martini.New() m.Use(middleware.Logger()) m.Use(martini.Recovery()) m.Use(martini.Static("public", martini.StaticOptions{SkipLogging: !base.DisableRouterLog})) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return &martini.ClassicMartini{m, r} }
func QuietMartini() *martini.ClassicMartini { r := martini.NewRouter() customMartini := martini.New() customMartini.Use(customLogger()) customMartini.Use(martini.Recovery()) customMartini.Use(martini.Static("public")) customMartini.MapTo(r, (*martini.Routes)(nil)) customMartini.Action(r.Handle) return &martini.ClassicMartini{customMartini, r} }
// newRouter creates a router with all the web service routes set func newRouter() martini.Router { r := martini.NewRouter() r.Get("/images/latest", getLastImage) r.Get("/users/top", getUsersTop) r.Get("/users/:user_id", getUser) r.Post("/messages/slack", addMessage) r.Get("/messages", getMessages) r.Get("/questions/current", getCurrentQuestion) r.Post("/slack/commands/tv", slackCommandTV) return r }