Example #1
0
func startGUI(addr string, m *model.Model) {
	router := martini.NewRouter()
	router.Get("/", getRoot)
	router.Get("/rest/version", restGetVersion)
	router.Get("/rest/model", restGetModel)
	router.Get("/rest/connections", restGetConnections)
	router.Get("/rest/config", restGetConfig)
	router.Get("/rest/need", restGetNeed)
	router.Get("/rest/system", restGetSystem)

	fs, err := embed.Unpack(Resources)
	if err != nil {
		panic(err)
	}

	go func() {
		mr := martini.New()
		mr.Use(embeddedStatic(fs))
		mr.Use(martini.Recovery())
		mr.Action(router.Handle)
		mr.Map(m)
		err := http.ListenAndServe(addr, mr)
		if err != nil {
			warnln("GUI not possible:", err)
		}
	}()

}
Example #2
0
// NewServer creates an instance of a martini server. The
// adapterInst parameter is the adapter type the server will
// use when dispatching requests.
func NewServer(adapterInst PanamaxAdapter) AdapterServer {
	s := martini.New()

	// Setup middleware
	s.Use(martini.Recovery())
	s.Use(martini.Logger())
	s.Use(mapEncoder)
	s.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		c.Map(adapterInst)
	})
	// Setup routes
	router := martini.NewRouter()
	router.Group(fmt.Sprintf("/%s", APIVersion), func(r martini.Router) {
		r.Get(`/services`, getServices)
		r.Get(`/services/:id`, getService)
		r.Post(`/services`, createServices)
		r.Put(`/services/:id`, updateService)
		r.Delete(`/services/:id`, deleteService)
		r.Get(`/metadata`, getMetadata)
	})

	// Add the router action
	s.Action(router.Handle)
	server := martiniServer{svr: s}

	return &server
}
Example #3
0
func startGUI(cfg GUIConfiguration, m *Model) {
	router := martini.NewRouter()
	router.Get("/", getRoot)
	router.Get("/rest/version", restGetVersion)
	router.Get("/rest/model", restGetModel)
	router.Get("/rest/connections", restGetConnections)
	router.Get("/rest/config", restGetConfig)
	router.Get("/rest/config/sync", restGetConfigInSync)
	router.Get("/rest/system", restGetSystem)
	router.Get("/rest/errors", restGetErrors)

	router.Post("/rest/config", restPostConfig)
	router.Post("/rest/restart", restPostRestart)
	router.Post("/rest/reset", restPostReset)
	router.Post("/rest/error", restPostError)
	router.Post("/rest/error/clear", restClearErrors)

	go func() {
		mr := martini.New()
		if len(cfg.User) > 0 && len(cfg.Password) > 0 {
			mr.Use(basic(cfg.User, cfg.Password))
		}
		mr.Use(embeddedStatic())
		mr.Use(martini.Recovery())
		mr.Use(restMiddleware)
		mr.Action(router.Handle)
		mr.Map(m)
		err := http.ListenAndServe(cfg.Address, mr)
		if err != nil {
			warnln("GUI not possible:", err)
		}
	}()
}
Example #4
0
func main() {
	// Load DB
	options := &bolt.Options{Timeout: 2 * time.Second}
	dbPath := path.Join(os.Getenv("BOLT_PATH"), "reminder.db")
	db, err := bolt.Open(dbPath, 0600, options)
	if err != nil {
		log.Fatalf("Error opening bolt DB: %v", err)
	}
	defer db.Close()

	// Schedule all (non-cancelled) Reminders
	rems, err := remind.GetAllReminders(db)
	if err != nil {
		log.Fatalf("Error getting reminders: %v\n", err)
	}

	runningReminders.Schedule(db, rems)

	//
	// Router, etc
	//

	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Action(r.Handle)

	m.Map(db)

	r.Post("/sms", incomingSMS)

	m.Run()
}
Example #5
0
func martiniInit() {
	m := martini.New()
	r := martini.NewRouter()

	m.Map(db)
	//m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	//m.Use(oauth2.Github(&oauth2.Options{
	// 	ClientId:	  "64a641523f31dd5bfe4b",
	// 	ClientSecret: "4fe3fbbca262835c424ca6a80aec6c6cb4228037",
	// 	RedirectURL:  "http://localhost:2714/github_callback",
	// 	Scopes:		  []string{"user:email"},
	//}))

	//r.Get("/", index)
	r.Get("/comments/:forum/:page", GetAllCommentsResource)
	r.Post("/comment", PostCommentHandler)
	//r.Get("/github_redirect", RedirectUrl)
	//r.Get("/github_callback", func(request *http.Request) string {
	// 	request.ParseForm()
	// 	return fmt.Sprintf("%+v", request)
	//})

	m.Use(martini.Static("ui"))
	m.Action(r.Handle)

	fmt.Println("Running on port " + viper.GetString("port"))

	sio.Handle("/", m)
	//http.Handle("/", m)
	//http.ListenAndServe(":"+viper.GetString("port"), m)
}
Example #6
0
func startGUI(addr string, m *Model) {
	router := martini.NewRouter()
	router.Get("/", getRoot)
	router.Get("/rest/version", restGetVersion)
	router.Get("/rest/model", restGetModel)
	router.Get("/rest/connections", restGetConnections)
	router.Get("/rest/config", restGetConfig)
	router.Get("/rest/config/sync", restGetConfigInSync)
	router.Get("/rest/need", restGetNeed)
	router.Get("/rest/system", restGetSystem)
	router.Get("/rest/errors", restGetErrors)

	router.Post("/rest/config", restPostConfig)
	router.Post("/rest/restart", restPostRestart)
	router.Post("/rest/error", restPostError)

	go func() {
		mr := martini.New()
		mr.Use(embeddedStatic())
		mr.Use(martini.Recovery())
		mr.Action(router.Handle)
		mr.Map(m)
		err := http.ListenAndServe(addr, mr)
		if err != nil {
			warnln("GUI not possible:", err)
		}
	}()
}
func TestMartiniSelectiveRouter(t *testing.T) {
	for _, test := range tests {
		w := httptest.NewRecorder()
		r := martini.NewRouter()

		done := make(chan bool)
		selectRoute(r, test.ExpectedMethod, func(rq *http.Request) {
			done <- true
		})

		req, err := http.NewRequest(test.Method, "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		OverrideRequestMethod(req, test.OverrideMethod)

		m := martini.New()
		m.Use(Override())
		m.Action(r.Handle)
		go m.ServeHTTP(w, req)
		select {
		case <-done:
		case <-time.After(30 * time.Millisecond):
			t.Errorf("Expected router to route to %s, got something else (%v).", test.ExpectedMethod, test)
		}
	}
}
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 BenchmarkCodegangstaMartini_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 routes() martini.Router {
	r := martini.NewRouter()
	r.Get("/", func() string {
		return "It works!"
	})
	r.Post("/capture", handleCapture)
	return r
}
Example #11
0
func newMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(middleware.Logger())
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{m, r}
}
Example #12
0
func init() {
	m = martini.New()
	r := martini.NewRouter()
	r.Get("/v2/catalog", GetCatalog)
	r.Put("/v2/service_instances/:id", CreateService)
	r.Delete("/v2/service_instances/:id", DeleteService)
	r.Put("/v2/service_instances/:instance_id/service_bindings/:id", BindService)
	r.Delete("/v2/service_instances/:instance_id/service_bindings/:id", UnbindService)
	m.Action(r.Handle)
}
Example #13
0
func AppServer() *Server {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Use(DB())

	m.Action(r.Handle)
	return &Server{m, r}
}
Example #14
0
func init() {
	m = martini.New()
	// Setup routes
	r := martini.NewRouter()
	r.Post(`/images`, postImage)
	r.Get(`/torrents`, getTorrent)
	r.Get(`/images/all`, getImagesList)
	r.Get(`/images`, getImages)
	// Add the router action
	m.Action(r.Handle)
}
Example #15
0
func newModern() *Modern { // customized martini.Classic
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.Action(r.Handle)

	return &Modern{
		Martini: m,
		Router:  r,
	}
}
Example #16
0
func main() {
	// runtime.GOMAXPROCS(runtime.NumCPU())
	// fmt.Printf("GOMAXPROCS is %d\n", runtime.GOMAXPROCS(0))

	// Server and middleware
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())

	r := martini.NewRouter()
	m.Action(r.Handle)

	r.Get("/", func() string {
		return "."
	})

	r.Any("/fetch", func(req *http.Request, res http.ResponseWriter) {
		err := req.ParseForm()
		if err != nil {
			renderMsg(res, 422, "Unable to parse parameters")
			return
		}

		// Grab params and set defaults
		urls := req.Form["url"]
		if len(urls) == 0 {
			urls = req.Form["url[]"]
		}
		maxtime, _ := strconv.Atoi(req.Form.Get("maxtime"))
		if maxtime == 0 {
			maxtime = MAXTIME
		}
		if len(urls) == 0 {
			renderMsg(res, 422, "Url parameter required")
			return
		}

		responses := httpFetch(urls, maxtime)

		if err != nil {
			renderMsg(res, 500, err.Error())
		} else {
			renderMsg(res, 200, responses)
		}
	})

	// Boot the server
	log.Println("** Purls", VERSION, "http server listening on", ADDR)
	log.Println("** with thruput:", THRUPUT, "maxtime:", MAXTIME)

	if err := http.ListenAndServe(ADDR, m); err != nil {
		log.Fatal(err)
	}
}
func newBenchmarkMartini() *martini.ClassicMartini {
	router := martini.NewRouter()
	base := martini.New()
	base.Action(router.Handle)

	m := &martini.ClassicMartini{base, router}
	m.Get("/benchmark", Languages(), func(result AcceptLanguages) {
		//b.Logf("Parsed languages: %s", result)
	})

	return m
}
Example #18
0
func createMartini(dbh *db.DBHandle) *martini.Martini {
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(
		render.Renderer(
			render.Options{
				IndentJSON: true,
			},
		),
	)

	m.Use(func(w http.ResponseWriter, req *http.Request) {
		if origin := req.Header.Get("Origin"); origin != "" {
			w.Header().Add("Access-Control-Allow-Origin", origin)
		}
		w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Add("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token")
		w.Header().Add("Access-Control-Allow-Credentials", "true")
	})
	m.Map(dbh)

	r := martini.NewRouter()
	r.Options("/api/1/people", send200)
	r.Get("/api/1/people", getPeople)
	r.Get("/api/1/people/:id", getPerson)
	r.Post("/api/1/people", createPerson)

	r.Get("/api/1/notes", getNotes)
	r.Options("/api/1/notes", send200)
	r.Post("/api/1/notes", createNote)
	r.Delete("/api/1/notes/:id", deleteNote)
	r.Options("/api/1/notes/:id", send200)

	r.Get("/api/1/notes/:id", getNote)
	r.Options("/api/1/notes/:id", send200)
	r.Put("/api/1/notes/:id", updateNote)

	r.Get("/api/1/todos", getTodos)
	r.Get("/api/1/todos/:id", getTodo)

	r.Post("/api/1/todos", createTodo)
	r.Options("/api/1/todos", send200)
	r.Put("/api/1/todos/:id", updateTodo)
	r.Options("/api/1/todos/:id", send200)
	r.Delete("/api/1/todos/:id", deleteTodo)

	m.Action(r.Handle)

	return m
}
func BenchmarkCodegangstaMartini_Simple(b *testing.B) {
	r := martini.NewRouter()
	m := martini.New()
	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)
	}
}
Example #20
0
func main() {
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	m := martini.New()

	r := martini.NewRouter()
	r.Get("/tracks", GetTracks)

	m.Action(r.Handle)
	m.Run()
}
func codegangstaMartiniRouterFor(namespaces []string, resources []string) http.Handler {
	router := martini.NewRouter()
	martini := martini.New()
	martini.Action(router.Handle)
	for _, ns := range namespaces {
		for _, res := range resources {
			router.Get("/"+ns+"/"+res, helloHandler)
			router.Post("/"+ns+"/"+res, helloHandler)
			router.Get("/"+ns+"/"+res+"/:id", helloHandler)
			router.Put("/"+ns+"/"+res+"/:id", helloHandler)
			router.Delete("/"+ns+"/"+res+"/:id", helloHandler)
		}
	}
	return martini
}
Example #22
0
func NewShortener(tde *kv.TiedotEngine) *martini.Martini {
	flag.Parse()
	app := martini.New()

	app.Map(tde)

	go countHits(tde)

	r := martini.NewRouter()
	r.Get("/", root)
	r.Post("/", newShort)
	r.Get("/:short", retrieve)
	r.Delete("/:short", remove)
	app.Action(r.Handle)
	return app
}
//
// Benchmarks for codegangsta/martini:
//
func BenchmarkCodegangstaMartiniSimple(b *testing.B) {
	r := martini.NewRouter()
	m := martini.New()
	m.Action(r.Handle)

	r.Get("/action", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(rw, "hello")
	})

	rw, req := testRequest("GET", "/action")

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		m.ServeHTTP(rw, req)
	}
}
Example #24
0
func main() {

	// START OMIT
	m := martini.New()

	// Specify what middleware to use
	m.Use(martini.Logger())
	m.Use(martini.Recovery())

	r := martini.NewRouter()
	r.Get("/ok", ok)
	r.Get("/panic", panicFunc)
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	http.ListenAndServe(":1810", m)
	// STOP OMIT
}
func init() {
	m = martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("Strict-Transport-Security", "max-age=60000")
	})
	m.Use(martini.Static("public"))
	m.Use(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})
	r := martini.NewRouter()
	r.Put("/candidates", mainHandler)
	m.Action(r.Handle)
	http.Handle("/", m)
}
Example #26
0
func makeService(ts tuplespace.RawTupleSpace, debug bool) *martini.Martini {
	m := martini.New()
	m.Use(martini.Recovery())
	if debug {
		m.Use(martini.Logger())
	}
	m.Use(server.SerializationMiddleware())

	m.MapTo(ts, (*tuplespace.RawTupleSpace)(nil))

	r := martini.NewRouter()
	r.Post("/tuplespace/", server.DeserializerMiddleware(SendRequest{}), Send)
	r.Get("/tuplespace/", server.DeserializerMiddleware(tuplespace.ReadRequest{}), Read)
	r.Delete("/tuplespace/", server.DeserializerMiddleware(tuplespace.ReadRequest{}), Take)

	m.Action(r.Handle)
	return m
}
Example #27
0
func main() {
	m := martini.New()
	route := martini.NewRouter()

	m.Map(retencoder.ReturnHandler())

	route.Get("/test", func() (int, interface{}) {
		result := &Some{Login: "******", Password: "******"}
		return http.StatusOK, result
	})

	m.Action(route.Handle)

	log.Println("Waiting for connections...")

	if err := http.ListenAndServe(":8000", m); err != nil {
		log.Fatal(err)
	}
}
Example #28
0
func init() {
	m = martini.New()
	// 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`, GetAlbums)
	r.Get(`/albums/:id`, GetAlbum)
	r.Post(`/albums`, AddAlbum)
	r.Put(`/albums/:id`, UpdateAlbum)
	r.Delete(`/albums/:id`, DeleteAlbum)
	// Inject database
	m.MapTo(db, (*DB)(nil))
	// Add the router action
	m.Action(r.Handle)
}
Example #29
0
func init() {
	m = martini.New()

	// middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())

	// injection
	m.MapTo(&UnitRepository{Repository: Repository{Type: Unit{}, Table: "units"}}, (*IUnitRepository)(nil))

	// routes
	r := martini.NewRouter()
	r.Get("/unit/:id", GetUnit)
	r.Get("/unit", GetAllUnits)
	r.Post("/unit", binding.Bind(Unit{}), AddUnit)
	r.Put("/unit", binding.Bind(Unit{}), UpdateUnit)
	r.Delete("/unit/:id", DeleteUnit)

	// wireup router action
	m.Action(r.Handle)
}
Example #30
0
func startGUI(cfg config.GUIConfiguration, m *model.Model) error {
	listener, err := net.Listen("tcp", cfg.Address)
	if err != nil {
		return err
	}

	router := martini.NewRouter()
	router.Get("/", getRoot)
	router.Get("/rest/version", restGetVersion)
	router.Get("/rest/model", restGetModel)
	router.Get("/rest/connections", restGetConnections)
	router.Get("/rest/config", restGetConfig)
	router.Get("/rest/config/sync", restGetConfigInSync)
	router.Get("/rest/system", restGetSystem)
	router.Get("/rest/errors", restGetErrors)
	router.Get("/rest/discovery", restGetDiscovery)

	router.Post("/rest/config", restPostConfig)
	router.Post("/rest/restart", restPostRestart)
	router.Post("/rest/reset", restPostReset)
	router.Post("/rest/shutdown", restPostShutdown)
	router.Post("/rest/error", restPostError)
	router.Post("/rest/error/clear", restClearErrors)
	router.Post("/rest/discovery/hint", restPostDiscoveryHint)

	mr := martini.New()
	if len(cfg.User) > 0 && len(cfg.Password) > 0 {
		mr.Use(basic(cfg.User, cfg.Password))
	}
	mr.Use(static)
	mr.Use(martini.Recovery())
	mr.Use(restMiddleware)
	mr.Action(router.Handle)
	mr.Map(m)

	go http.Serve(listener, mr)

	return nil
}