Пример #1
0
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))

}
Пример #2
0
func init() {
	m = martini.New()
	//setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))
}
Пример #3
0
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)
	}
}
Пример #4
0
func Test_GitHubAuth(t *testing.T) {
	recorder := httptest.NewRecorder()

	secret := "secret"
	signature := "sha1=5d61605c3feea9799210ddcb71307d4ba264225f"
	body := "{}"

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

	r, _ := http.NewRequest("GET", "foo", bytes.NewReader([]byte(body)))
	r.Header.Set("X-Hub-Signature", signature)
	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())
	}
}
Пример #5
0
func TestRestErrorResult(t *testing.T) {
	m := martini.New()
	recorder := httptest.NewRecorder()
	m.Use(rest.RestPostHandler())
	m.Use(func(c martini.Context, res http.ResponseWriter, req *http.Request) {

		err := &rest.RestError{-1000, "12"}
		c.MapTo(err, (*error)(nil))
	})

	m.ServeHTTP(recorder, (*http.Request)(nil))

	if recorder.Code != http.StatusOK {
		t.Error("failed status")
		return
	}

	if recorder.Header().Get("Content-Type") != "application/json; charset=utf-8" {
		t.Error("failed content type")
		return
	}

	var returnObj rest.RestReturnObj

	if err := json.Unmarshal(recorder.Body.Bytes(), &returnObj); err != nil {
		t.Error("json decode failed")
		return
	}

	if returnObj.ErrorCode != -1000 {
		t.Error("error code failed")
		return
	}

}
Пример #6
0
func HandlerFromMartini(handler martini.Handler) http.Handler {
	m := martini.New()
	m.Use(handler)
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		m.ServeHTTP(rw, req)
	})
}
Пример #7
0
// create new helper, this object will be used for globar service for martini middleware
func New() *MartiniHelper {
	this := &MartiniHelper{inject.New()}
	retHandler := martini.New().Get(reflect.TypeOf(martini.ReturnHandler(nil))).Interface()
	// retHandler := martini.defaultReturnHandler()
	this.Map(retHandler)
	return this
}
Пример #8
0
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")
		}
	}
}
Пример #9
0
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)
}
Пример #10
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())
	}
}
Пример #11
0
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)
}
Пример #12
0
// 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")
}
Пример #13
0
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)
}
Пример #14
0
func Test_ResponseWriter_Hijack(t *testing.T) {
	hijackable := newHijackableResponse()

	m := martini.New()
	m.Use(All())
	m.Use(func(rw http.ResponseWriter) {
		if hj, ok := rw.(http.Hijacker); !ok {
			t.Error("Unable to hijack")
		} else {
			hj.Hijack()
		}
	})

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

	r.Header.Set(HeaderAcceptEncoding, "gzip")
	m.ServeHTTP(hijackable, r)

	if !hijackable.Hijacked {
		t.Error("Hijack was not called")
	}
}
Пример #15
0
func startMartini() {
	mux := martini.NewRouter()
	mux.Get("/hello", martiniHandlerWrite)
	martini := martini.New()
	martini.Action(mux.Handle)
	http.ListenAndServe(":"+strconv.Itoa(port), martini)
}
Пример #16
0
// 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)
}
Пример #17
0
/*
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 TestKeystoneValidUncachedToken(t *testing.T) {
	token := "token"

	// Set up mock token validator - one auth attempt is expected in this test
	testTokenValidator := new(MockTokenValidator)
	testTokenValidator.On("CheckToken", token).Return(true)

	// Set up mock cache - the middleware should try to get and set the token
	testCache := new(MockCache)
	testCache.On("Get", token).Return("", errors.New("test error"))
	testCache.On("Set", token, "authorized").Return(nil)

	// Dummy martini
	m := martini.New()
	m.Use(Keystone(testTokenValidator, testCache))
	m.Use(func(res http.ResponseWriter, req *http.Request, token Token) {
		res.Write([]byte(token))
	})

	// Send request to martini
	recorder := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "foo", nil)
	r.Header.Add("X-Auth-Token", token)
	m.ServeHTTP(recorder, r)

	// Assert mock expectations
	testTokenValidator.AssertExpectations(t)
	testCache.AssertExpectations(t)

	// Assert http response expectations
	assert.Equal(t, recorder.Code, 200, "Expected: 200")
	assert.Equal(t, recorder.Body.String(), token, "Expected: "+token)
}
Пример #19
0
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()
}
Пример #20
0
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))
}
Пример #21
0
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)
}
Пример #22
0
// NewWebService creates a new web service ready to run.
func NewWebService() *martini.Martini {
	m := martini.New()
	m.Handlers(loggerMiddleware(), martini.Recovery(), gzip.All())
	r := newRouter()
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return m
}
Пример #23
0
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}
}
Пример #24
0
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)
	}
}
Пример #25
0
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}
}
Пример #26
0
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}
}
Пример #27
0
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}
}
Пример #28
0
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}
}
Пример #29
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)
	}
}
Пример #30
0
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}
}