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)
}
Esempio n. 2
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)
		}
	}()

}
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")
		}
	}
}
Esempio n. 4
0
func Test_BasicAuth(t *testing.T) {
	recorder := httptest.NewRecorder()

	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("foo:bar"))

	m := martini.New()
	m.Use(Basic("foo", "bar"))
	m.Use(func(res http.ResponseWriter, req *http.Request) {
		res.Write([]byte("hello"))
	})

	r, _ := http.NewRequest("GET", "foo", nil)

	m.ServeHTTP(recorder, r)

	if recorder.Code != 401 {
		t.Error("Response not 401")
	}

	if recorder.Body.String() == "hello" {
		t.Error("Auth block failed")
	}

	recorder = httptest.NewRecorder()
	r.Header.Set("Authorization", auth)
	m.ServeHTTP(recorder, r)

	if recorder.Code == 401 {
		t.Error("Response is 401")
	}

	if recorder.Body.String() != "hello" {
		t.Error("Auth failed, got: ", recorder.Body.String())
	}
}
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)
		}
	}
}
Esempio n. 6
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()
}
Esempio n. 7
0
func main() {
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(nrscstatic.NrscStatic("public", true))
	http.ListenAndServe(":8080", m)
}
Esempio n. 8
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)
		}
	}()
}
Esempio n. 9
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)
}
Esempio n. 10
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)
		}
	}()
}
Esempio n. 11
0
func Test_Preflight(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.New()
	m.Use(Allow(&Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"PUT", "PATCH"},
		AllowHeaders:    []string{"Origin", "X-whatever"},
	}))

	r, _ := http.NewRequest("OPTIONS", "foo", nil)
	r.Header.Add(headerRequestMethod, "PUT")
	r.Header.Add(headerRequestHeaders, "X-whatever")
	m.ServeHTTP(recorder, r)

	methodsVal := recorder.HeaderMap.Get(headerAllowMethods)
	headersVal := recorder.HeaderMap.Get(headerAllowHeaders)

	if methodsVal != "PUT,PATCH" {
		t.Errorf("Allow-Methods is expected to be PUT,PATCH, found %v", methodsVal)
	}

	if headersVal != "X-whatever" {
		t.Errorf("Allow-Headers is expected to be X-whatever, found %v", headersVal)
	}
}
Esempio n. 12
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
}
func main() {
	Db = dbSetup()

	m := martini.New()
	//m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Action(routes().Handle)
	m.Run()
}
Esempio n. 14
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)
}
Esempio n. 15
0
func Benchmark_WithoutCORS(b *testing.B) {
	recorder := httptest.NewRecorder()
	m := martini.New()

	b.ResetTimer()
	for i := 0; i < 100; i++ {
		r, _ := http.NewRequest("PUT", "foo", nil)
		m.ServeHTTP(recorder, r)
	}
}
Esempio n. 16
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}
}
Esempio n. 17
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,
	}
}
Esempio n. 18
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)
}
Esempio n. 19
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)
	}
}
Esempio n. 20
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}
}
Esempio n. 21
0
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
}
Esempio n. 22
0
func TestInMartini(t *testing.T) {
	m := martini.New()
	m.Use(Prefix("/foo"))
	m.Use(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/bar" {
			t.Fatalf("Strip Prefix Failed")
		}
	})
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/foo/bar", nil)
	m.ServeHTTP(w, r)
}
Esempio n. 23
0
func Test_GzipAll(t *testing.T) {
	// Set up
	recorder := httptest.NewRecorder()
	before := false

	m := martini.New()
	m.Use(All())
	m.Use(func(r http.ResponseWriter) {
		r.(martini.ResponseWriter).Before(func(rw martini.ResponseWriter) {
			before = true
		})
	})

	r, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}

	m.ServeHTTP(recorder, r)

	// Make our assertions
	_, ok := recorder.HeaderMap[HeaderContentEncoding]
	if ok {
		t.Error(HeaderContentEncoding + " present")
	}

	ce := recorder.Header().Get(HeaderContentEncoding)
	if strings.EqualFold(ce, "gzip") {
		t.Error(HeaderContentEncoding + " is 'gzip'")
	}

	recorder = httptest.NewRecorder()
	r.Header.Set(HeaderAcceptEncoding, "gzip")
	m.ServeHTTP(recorder, r)

	// Make our assertions
	_, ok = recorder.HeaderMap[HeaderContentEncoding]
	if !ok {
		t.Error(HeaderContentEncoding + " not present")
	}

	ce = recorder.Header().Get(HeaderContentEncoding)
	if !strings.EqualFold(ce, "gzip") {
		t.Error(HeaderContentEncoding + " is not 'gzip'")
	}

	if before == false {
		t.Error("Before hook was not called")
	}
}
Esempio n. 24
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
}
Esempio n. 25
0
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)
	}
}
Esempio n. 26
0
func Test_AllowAll(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.New()
	m.Use(Allow(&Options{
		AllowAllOrigins: true,
	}))

	r, _ := http.NewRequest("PUT", "foo", nil)
	m.ServeHTTP(recorder, r)

	if recorder.HeaderMap.Get(headerAllowOrigin) != "*" {
		t.Errorf("Allow-Origin header should be *")
	}
}
Esempio n. 27
0
func Test_DefaultAllowHeaders(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.New()
	m.Use(Allow(&Options{
		AllowAllOrigins: true,
	}))

	r, _ := http.NewRequest("PUT", "foo", nil)
	m.ServeHTTP(recorder, r)

	headersVal := recorder.HeaderMap.Get(headerAllowHeaders)
	if headersVal != "Origin,Accept,Content-Type,Authorization" {
		t.Errorf("Allow-Headers is expected to be Origin,Accept,Content-Type,Authorization; found %v", headersVal)
	}
}
Esempio n. 28
0
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
}
Esempio n. 29
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()
}
//
// 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)
	}
}