Example #1
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))
}
Example #2
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()
}
Example #3
0
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)
}
Example #4
0
func init() {
	m = martini.New()
	//setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))
}
Example #5
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(martini.Logger())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	store := sessions.NewCookieStore([]byte(CookieSecret))
	m.Use(sessions.Sessions("bunkaisession", store))
	log.Println("env is", martini.Env)
	m.Map(martini.Env)

	m.Group("/", func(m martini.Router) {
		m.Get("", Home)
	}, AssetMap)

	m.Group("/api", func(m martini.Router) {
		m.Post("/login", PostLogin)
		m.Post("/users", UserCreate)

		m.Group("/sentences", func(m martini.Router) {
			m.Post("", SentenceCreate)
			m.Get("", SentenceList)
			m.Delete("/:id", SentenceDelete)
		}, RequireLogin)

		m.Group("/users", func(m martini.Router) {
			m.Post("/logout", Logout)
			m.Get("/me", UserGet)
		}, RequireLogin)
	})

	m.Run()
}
Example #6
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)
	}
}
Example #7
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)
}
Example #8
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))

}
Example #9
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)
}
Example #10
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")
}
Example #11
0
func main() {
	var v Vcap
	err := json.Unmarshal([]byte(os.Getenv("VCAP_APPLICATION")), &v)
	if err != nil {
		log.Fatal(err)
	}

	m := martini.Classic()

	app_uri := v.Uris[0]
	cfhost := strings.SplitAfterN(app_uri, ".", 2)[1]
	oauthOpts := &gooauth2.Options{
		ClientID:     os.Getenv("CLIENT_ID"),
		ClientSecret: os.Getenv("CLIENT_SECRET"),
		RedirectURL:  "https://" + app_uri + "/oauth2callback",
		Scopes:       []string{""},
	}

	cf := oauth2.NewOAuth2Provider(
		oauthOpts,
		"https://login."+cfhost+"/oauth/authorize",
		"http://uaa."+cfhost+"/oauth/token",
	)

	m.Get("/oauth2error", func() string {
		log.Fatal("oAuth error")
		return "oAuth error :("
	})

	m.Handlers(
		sessions.Sessions("session", sessions.NewCookieStore([]byte("secret123"))),
		cf,
		oauth2.LoginRequired,
		martini.Logger(),
		martini.Static("public"),
	)

	m.Get("/", func(tokens oauth2.Tokens) string {

		if tokens.IsExpired() {
			return "Not logged in, or the access token is expired"
		}

		// oAuth user information from the UAA
		body := oauth_get("http://uaa."+cfhost+"/userinfo", tokens)
		var u User
		err := json.Unmarshal(body, &u)
		if err != nil {
			log.Fatal(err)
		}

		// Example actual API call to get the list of spaces the user belongs to
		space_body := oauth_get("http://api."+cfhost+"/v2/users/"+u.User_id+"/spaces", tokens)

		return fmt.Sprintf("User ID: %s\n\nSpaces info: %s", u.User_id, space_body)
	})

	m.Run()
}
Example #12
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)
	}
}
Example #13
0
func main() {

	config, err := config.Load()
	if err != nil {
		log.Fatal(err)
	}

	fishhubService, err := fishhub.NewService(config.MongoURL)
	if err != nil {
		log.Fatal(err)
	}

	sessionService, err := session.NewService(config.MongoURL)
	if err != nil {
		log.Fatal(err)
	}

	store := sessions.NewCookieStore([]byte("@!#$%^&*"))

	m := martini.Classic()

	m.Map(fishhubService)
	m.Map(sessionService)

	m.Use(sessions.Sessions("go_session", store))

	// Setup routes
	m.Get("/", home)

	m.Group("/users", func(r martini.Router) {
		r.Post("", binding.Bind(UserForm{}), NewUser)
		r.Get("/:id", GetUser)
		r.Put("/update/:id", UpdateUser)
		r.Delete("/delete/:id", DeleteUser)
	})

	m.Group("/login", func(r martini.Router) {
		r.Post("", binding.Bind(LoginForm{}), CheckCredential)
	})

	m.Handlers(
		render.Renderer(render.Options{
			Delims: render.Delims{"<%", "%>"},
		}),
		martini.Logger(),
		martini.Static("public"),
	)

	m.NotFound(func(r render.Render) {
		r.HTML(404, "404", nil)
	})

	err = http.ListenAndServe(":"+config.Port, m)
	if err != nil {
		log.Fatal(err)
	}

}
Example #14
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}
}
Example #15
0
func main() {
	c := &gosteno.Config{
		Sinks: []gosteno.Sink{
			gosteno.NewIOSink(os.Stdout),
		},
		Level:     gosteno.LOG_DEBUG,
		Codec:     gosteno.NewJsonPrettifier(0),
		EnableLOC: true,
	}
	gosteno.Init(c)

	logger := gosteno.NewLogger("atk_instances")

	conf := config.NewConfig()

	m := martini.Classic()

	key, err := atkoauth2.TokenKey(conf.TokenKeyUrl)
	if err != nil {
		logger.Error(err.Error())
		return
	}

	m.Handlers(
		atkoauth2.ResourceServer(key),
		martini.Logger(),
		render.Renderer(render.Options{IndentJSON: true}),
	)

	m.Get("/rest/orgs/:id/atkinstances", func(params martini.Params, t *jwt.Token, r render.Render) {

		cloudController := cc.NewRestCloudController(conf.ApiUrl, t.Raw)

		spaceSummaryHelper := service.NewSpaceSummaryHelper()

		srv := service.NewAtkListService(cloudController, spaceSummaryHelper)

		if len(conf.CommonService) == 0 {
			conf.CommonService = "postgres"
		}

		//TODO: check id param

		instances, err := srv.GetAllInstances(conf.ServiceLabel,
			conf.ScoringEngineLabel,
			conf.CommonService,
			params["id"])
		if err != nil {
			r.JSON(500, err.Error())
		}

		r.JSON(200, instances)
	})

	m.Run()
}
Example #16
0
// getSilentMartini returns a ClassicMartini with logging disabled.
func getSilentMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	if *verboseMartini {
		m.Use(martini.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 #17
0
func newClassic() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()

	// 日志
	if Conf.Debug {
		m.Use(martini.Logger())
	}

	// 捕获所有错误
	m.Use(martini.Recovery())

	// 静态处理
	m.Use(martini.Static(Conf.StaticDir, Conf.StaticOptions))

	// Session
	store, _ := sessions.NewRediStore(10, "tcp", Conf.RedisAddress, "", []byte(Conf.SessionSecret))
	store.Options(Conf.SessionOptions)
	m.Use(sessions.Sessions(Conf.SessionName, store))

	// csrf
	m.Use(csrf.CsrfInstance.Generate(Conf.CsrfOptions))

	// 缓存中间件
	m.Use(func(c martini.Context, req *http.Request, w http.ResponseWriter) {
		// 覆写ResponseWriter接口
		res := Lib.Http.NewResponseWriter(req, w)
		c.MapTo(res, (*http.ResponseWriter)(nil))

		// Api请求
		if strings.HasPrefix(req.URL.String(), "/api") {
			// 响应类型:Json
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			// GET请求读取缓存
			if !Conf.Debug && req.Method == "GET" {
				// 缓存没过期
				if cache, err := redis.RedisInstance.Get("url-" + req.URL.String()); err == nil {
					w.Write(cache)
					return
				}
			}
		} else {
			// 其他类型请求响应类型:Html
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
		}
	})

	// 返回可以直接调用的路由
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	return &martini.ClassicMartini{m, r}
}
Example #18
0
func main() {
	m := martini.New()

	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(render.Renderer())

	r := conf.Router()
	m.MapTo(r, (*martini.Router)(nil))
	m.Action(r.Handle)

	m.Run()
}
Example #19
0
func NewServer() *Server {
	s := &Server{}
	r := martini.NewRouter()
	r.Get("/ping", s.Ping)
	r.Post("/exec", s.ExecCommand)
	r.Put("/upload", s.PutFile)

	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	s.m = m
	return s
}
Example #20
0
func makeDirtyMartini() (*martini.Martini, martini.Router) {
	r := martini.NewRouter()
	m := martini.New()

	m.Use(func(c martini.Context, req *http.Request) {
		c.MapTo(appengine.NewContext(req), (*appengine.Context)(nil))
	})

	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	return m, r
}
Example #21
0
func init() {
	m = martini.New()
	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))
	m.Use(MapEncoder)
	// Setup routes
	r := martini.NewRouter()

	// Inject database
	m.MapTo(models.Dbm, (*gorp.SqlExecutor)(nil))
	// Add the router action
	m.Action(r.Handle)
}
Example #22
0
File: main.go Project: tcyd/gobed
func init() {
	m = martini.New()
	// Setup config
	conf, err := goconf.ReadConfigFile(`app.conf`)
	if err != nil {
		panic(err)
	}
	m.Map(conf)

	// Setup enviroment
	env, err := conf.GetString(`default`, `env`)
	if err != nil {
		env = `dev`
	}
	switch env {
	case `prod`:
		martini.Env = martini.Prod
	case `test`:
		martini.Env = martini.Test
	default:
		martini.Env = martini.Dev
	}

	// Setup middlewares
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Use(martini.Logger())

	staticPath, err := conf.GetString(`default`, `staticpath`)
	if err != nil {
		panic(err)
	}
	m.Use(martini.Static(staticPath))

	// sessionRedisHost, _ := conf.GetString(`sessionredis`, `host`)
	// sessionRedisPort, _ := conf.GetString(`sessionredis`, `port`)
	// sessionRedisPassword, _ := conf.GetString(`sessionredis`, `password`)
	// sessionRedisKey, _ := conf.GetString(`sessionredis`, `key`)
	// //store := sessions.NewCookieStore([]byte("secret123"))
	// store, err := sessions.NewRediStore(10, `tcp`, sessionRedisHost+`:`+sessionRedisPort, sessionRedisPassword, []byte(sessionRedisKey))
	// if err != nil {
	// 	panic(err)
	// }
	// m.Use(sessions.Sessions("session", store))

	// Setup routes
	Routes(m)
}
Example #23
0
func main() {
	m := martini.New()

	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))

	r := martini.NewRouter()

	r.Get("/connect", websocket.Handler(connect).ServeHTTP)
	r.Get("/:id", joinGame)

	m.Action(r.Handle)

	m.Run()
}
Example #24
0
func apiHandler(router *Router) http.Handler {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Action(r.Handle)
	m.Map(router)

	r.Post("/routes", binding.Bind(strowger.Route{}), createRoute)
	r.Put("/routes", binding.Bind(strowger.Route{}), createOrReplaceRoute)
	r.Get("/routes", getRoutes)
	r.Get("/routes/:route_type/:route_id", getRoute)
	r.Delete("/routes/:route_type/:route_id", deleteRoute)
	return m
}
Example #25
0
func buildMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))

	// Map encoder conditionally based on pretty print request param
	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		pretty, _ := strconv.ParseBool(r.URL.Query().Get("pretty"))
		c.MapTo(encoder.JSONEncoder{PrettyPrint: pretty}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Action(r.Handle)
	return &martini.ClassicMartini{Martini: m, Router: r}
}
Example #26
0
func init() {
	// Initialize store
	store = *GetStoreSession()

	// Initialize martini
	m = martini.New()

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

	// Setup routes
	r := martini.NewRouter()
	r.Get(`/shows`, Authenticate, ApiShowsGetAll)
	r.Get(`/shows/:id`, Authenticate, ApiShowsGetOne)
	r.Put(`/shows/:id`, Authenticate, ApiShowsPutOne)
	r.Get(`/shows/:showId/seasons`, ApiSeasonsGetAllByShow)
	r.Get(`/shows/:showId/seasons/:seasonNumber/episodes`, ApiEpisodesGetAllByShowAndSeason)
	r.Get(`/shows/:showId/seasons/:seasonNumber/episodes/:episodeNumber`, ApiEpisodesGetOneByShowAndSeasonAndEpisode)
	r.Post(`/files`, ApiFilesPost)
	r.Patch(`/files`, ApiProcessFiles)
	r.Get(`/register`, ApiUsersRegister)
	r.Post(`/login`, ApiUsersLogin)
	r.Get(`/rss`, ApiRss)

	// Allow CORS
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
		AllowHeaders:     []string{"Origin", "Content-Type", "X-API-TOKEN"},
		ExposeHeaders:    []string{"Content-Length", "Content-Type"},
		AllowCredentials: true,
	}))
	// Other stuff
	m.Use(func(c martini.Context, w http.ResponseWriter) {
		// Inject JSON Encoder
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		// Force Content-Type
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	// Inject database
	m.MapTo(store, (*Store)(nil))
	// Add the router action
	m.Action(r.Handle)
}
Example #27
0
func NewServer() *Server {
	s := &Server{}
	r := martini.NewRouter()
	r.Group("/v1", func(r martini.Router) {
		r.Get("/ping", s.ping)
		r.Post("/provision", s.provision)
		r.Get("/runs/:id/wait", s.wait)
	})

	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Action(r.Handle)
	s.handler = m
	s.runs = make(map[string]*runContext)
	return s
}
Example #28
0
func init() {

	m = martini.New()
	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(MapEncoder)
	// Setup routes()
	r := martini.NewRouter()
	r.Get("/", func(r render.Render) {
		r.JSON(200, map[string]interface{}{"hello": "world!"})
	})

	r.Post("/registerEvent", RegisterEvent)

	// Add the router action
	m.Action(r.Handle)
}
Example #29
0
func main() {
	flag.Parse()
	m := martini.New()
	r := martini.NewRouter()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	var pool = redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", *redisAddress)
		if err != nil {
			panic(err)
		}
		_, err = c.Do("SELECT", *database)
		if err != nil {
			panic(err)
		}
		return c, err
	}, *maxConnections)
	defer pool.Close()
	m.Map(pool)

	if os.Getenv("DEV") == "1" {
		m.Use(martini.Static("resources/public"))
	}

	f, _ := ioutil.ReadFile("resources/public/index.html")
	t, _ := template.New("index").Parse(string(f))
	m.Map(t)

	r.Post("/save", Save)
	r.Post("/:id/:sum", Save)

	r.Get("/", Load)
	r.Get("/:id", Load)
	r.Get("/:id/:sum", Load)

	if os.Getenv("DEV") == "1" {
		m.Run()
	} else {
		m.RunOnAddr(*bind)
	}
}
Example #30
0
func main() {
	consulAddress := mustGetEnvVar("CONSUL_HTTP_ADDR")
	environment := mustGetEnvVar("ENVIRONMENT")
	serviceName := mustGetEnvVar("SERVICE_NAME")

	conf, _ := setupConfig(serviceName, environment, consulAddress)
	//pull config and pass it around
	conf.MustGetDuration(configKeyBalancerTTL)

	// use loadbalancer to lookup services and db locations if necessary
	// Each request should repeat the lookup to make sure that this app
	// follows any services that move
	// s, err := loadbalancer.FindService("foo")

	//setup martini
	m := martini.New()
	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())

	// Setup routes
	router := martini.NewRouter()
	router.Group("/v1", func(v1router martini.Router) {
		//Setup v1 routes
		v1router.Group("/test", func(r martini.Router) {
			r.Get("/ping", test.Ping())
		})
	})

	// Add the router action
	m.Action(router.Handle)

	// Inject dependencies
	m.Use(func(c martini.Context, w http.ResponseWriter) {
		enc := negotiator.JsonEncoder{PrettyPrint: false}
		cn := negotiator.NewContentNegotiator(enc, w)
		cn.AddEncoder(negotiator.MimeJSON, enc)
		c.MapTo(cn, (*negotiator.Negotiator)(nil))
	})

	// Start up the server
	m.RunOnAddr(":8080")
}