示例#1
0
func (this *Server) Run(withRandomPort ...bool) {
	this.Martini.Use(cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"PUT", "PATCH", "DELETE", "GET", "OPTIONS", "POST"},
		AllowCredentials: true,
	}))
	this.Martini.Use(render.Renderer())

	this.Martini.Group("/eureka", func(r martini.Router) {
		for _, request := range this.getRequestsEureka() {
			request.SetRoutes(r)
		}
	})
	this.registerJobsRoutes()
	if len(withRandomPort) > 0 && withRandomPort[0] {
		listener, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			loggerServer.Severe("Error when getting a free random port: %v", err.Error())
		}
		host := listener.Addr().String()
		listener.Close()
		this.Martini.RunOnAddr(host)
	} else if config.GetConfig().Host != "" {
		this.Martini.RunOnAddr(config.GetConfig().Host)
	} else {
		this.Martini.Run()
	}

}
示例#2
0
func main() {
	api := &api.API{
		ApiKey: "122cc483be92bd806b696e7d458596ac",
		DataCacheRenewalInterval: 15,
	}
	api.Setup()
	go api.CyclicCacheRenewal()

	m := martini.Classic()
	m.Map(api)

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowCredentials: true,
	}))

	m.Use(func(c martini.Context, w http.ResponseWriter) {
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Get("/photos/:name", func(params martini.Params,
		enc encoder.Encoder) (int, []byte) {
		name, ok := params["name"]

		if ok {
			photos, _ := api.GetPhotosForUser(name)
			return http.StatusOK, encoder.Must(enc.Encode(photos))
		}

		return 404, []byte("Not Found")
	})
	m.Run()
}
示例#3
0
func (r *RestServer) listen() error {

	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	// m.Map(r.TaskModel)

	task := NewTaskRouter()
	task.scheduler = r.Scheduler

	m.Group("/rest/v1/tasks", task.Register)

	listenAddress := fmt.Sprintf(":%d", config.MustInt("app-scheduler.rest.port"))

	r.log.Infof("Listening at %s", listenAddress)

	srv := &http.Server{Addr: listenAddress, Handler: m}
	ln, err := net.Listen("tcp", listenAddress)
	if err != nil {
		return err
	}

	return srv.Serve(listener{
		TCPListener: ln.(*net.TCPListener),
		stop:        make(chan struct{}),
	})
}
示例#4
0
func (h *HTTPService) Start() {
	fmt.Println("Object Store Listening on Port : 3000")
	m := martini.Classic()
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"securityToken", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))
	//READ BY KEY
	m.Get("/:namespace/:class/:id", handleRequest)
	//READ BY KEYWORD
	m.Get("/:namespace/:class", handleRequest)
	//Get all classes
	m.Post("/:namespace", handleRequest)
	//READ ADVANCED, INSERT
	m.Post("/:namespace/:class", handleRequest)

	//FILE RECIEVER
	m.Post("/:namespace/:class/:id", uploadHandler)
	//UPDATE
	m.Put("/:namespace/:class", handleRequest)
	//DELETE
	m.Delete("/:namespace/:class", handleRequest)

	m.Run()
}
示例#5
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")
}
示例#6
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)
}
示例#7
0
func App() *martini.ClassicMartini {
	m := martini.Classic()

	m.Use(gzip.All())

	m.Use(render.Renderer(render.Options{
		Directory: "templates",
	}))

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Get("", Index)

	m.Group("/repos", func(r martini.Router) {
		r.Get("", ReposIndex)
		r.Get("/:name", ReposShow)
	})

	m.Group("/orgs", func(r martini.Router) {
		r.Get("", OrgsIndex)
		r.Get("/:id", OrgsShow)
	})

	m.Group("/users", func(r martini.Router) {
		r.Get("", UserIndex)
		r.Get("/:id", UserShow)
	})

	m.Get("/stats", StatsIndex)
	m.Get("/issues", IssuesIndex)

	return m
}
示例#8
0
// CORS is a middleware to handle CORS requests
func CORS(h http.Handler) http.Handler {
	f := cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"PUT", "PATCH", "DELETE", "POST"},
	})
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f(w, r)
		h.ServeHTTP(w, r)
	})
}
func main() {
	var (
		newrelicLicense = os.Getenv("NEWRELIC_LICENSE")
		newrelicName    = os.Getenv("NEWRELIC_NAME")
	)
	if newrelicLicense != "" && newrelicName != "" {
		agent := gorelic.NewAgent()
		agent.Verbose = true
		agent.NewrelicLicense = os.Getenv("NEWRELIC_LICENSE")
		agent.NewrelicName = os.Getenv("NEWRELIC_NAME")
		agent.Run()
	}

	m := martini.Classic()
	m.Get("/", func() string {
		return "Hello world!"
	})

	var logger *log.Logger
	logger = m.Injector.Get(reflect.TypeOf(logger)).Interface().(*log.Logger)

	m.Post("**", func(res http.ResponseWriter, req *http.Request) (int, string) {
		var (
			contentTypeHeader []string
			contentType       string
		)
		contentTypeHeader = req.Header["Content-Type"]
		if len(contentTypeHeader) > 0 {
			contentType = contentTypeHeader[0]
		} else {
			return 400, "Content-Type header is mandatory"
		}
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			return 400, "Invalid request body"
		}
		if contentType == "application/x-php" {
			qsa := toMapStringString(req.URL.Query())
			return checkPhp(res, string(body[:]), qsa)
		}
		return 415, "Content-Type not currently supported"
	})

	var corsOrigins = os.Getenv("CORS_ORIGINS")
	if corsOrigins != "" {
		logger.Println("activating CORS: " + corsOrigins)
		m.Use(cors.Allow(&cors.Options{
			AllowOrigins: strings.Split(corsOrigins, ","),
			AllowMethods: []string{"GET", "POST"},
			AllowHeaders: []string{"Origin", "Content-Type"},
		}))
	}

	m.Run()
}
示例#10
0
func NewAPI() *API {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:  []string{"*"},
		AllowMethods:  []string{"POST", "GET"},
		ExposeHeaders: []string{"Content-Length"},
	}))
	m.Use(staticbin.Static("web", Asset))
	return &API{m}
}
示例#11
0
func main() {

	if conf, e := LoadConfig("conf/string_keeper.conf"); e != nil {
		if os.IsNotExist(e) {
			fmt.Println("'conf/string_keeper.conf' not exist, it will use default config.")
			keeperConf = DefaultConfig()
		} else {
			fmt.Printf("load config file 'conf/string_keeper.conf' failed, err: %s\n", e.Error())
			os.Exit(1)
		}
	} else {
		keeperConf = conf
	}

	m := martini.Classic()

	m.Post("/", GetBucketString)

	m.Get("/ping", func() string {
		return "pong"
	})

	if cwd, e := os.Getwd(); e != nil {
		fmt.Printf("get current dir failed, err: %s", e.Error())
		os.Exit(1)
	} else if !filepath.IsAbs(cwd) {
		if absPath, e := filepath.Abs(cwd); e != nil {
			fmt.Printf("get current dir abs path failed, err: %s", e.Error())
			os.Exit(1)
			return
		} else {
			resDir = filepath.Join(absPath, "public")
		}
	} else {
		resDir = filepath.Join(cwd, "public")
	}

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     keeperConf.HTTP.CORS.AllowOrigins,
		AllowMethods:     keeperConf.HTTP.CORS.AllowMethods,
		AllowHeaders:     keeperConf.HTTP.CORS.AllowHeaders,
		ExposeHeaders:    keeperConf.HTTP.CORS.ExposeHeaders,
		AllowCredentials: keeperConf.HTTP.CORS.AllowCerdentials,
	}))

	if keeperConf.ACL.AuthEnabled {
		m.Use(auth.BasicFunc(AuthCheck))
	} else {
		m.Map(auth.User(""))
	}

	m.RunOnAddr(keeperConf.HTTP.Address)
}
示例#12
0
文件: server.go 项目: jshrake/pollr
func (app *App) SetUpMiddleware(config *pollr.Config) {
	// Setup CORS
	app.m.Use(cors.Allow(&cors.Options{
		AllowCredentials: true,
		AllowOrigins:     []string{config.WebAddress},
		AllowMethods:     []string{"GET", "POST", "PUT"},
		AllowHeaders:     []string{"Origin", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
	}))

	// Session handling
	app.m.Use(sessions.Sessions("pollr_session", sessions.NewCookieStore([]byte(config.AppSecret))))
}
示例#13
0
func main() {
	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "GET", "POST", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "content-type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	session, err := mgo.Dial("localhost")

	if err != nil {
		panic(err)
	}

	defer session.Close()

	m.Map(session)

	m.Group("/foods", func(r martini.Router) {
		r.Get("", GetFood)
		r.Get("/:id", GetFood)
		r.Get("/queries/:name", GetFoodByName)
		r.Post("/new", binding.Bind(d.Food{}), NewFood)
		r.Put("/update/:id", binding.Bind(d.Food{}), UpdateFood)
		r.Delete("/delete/:id", DeleteFood)
	})

	m.Group("/recipes", func(r martini.Router) {
		r.Get("", GetRecipe)
		r.Get("/:id", GetRecipe)
		r.Post("", binding.Bind(Recipe{}), NewRecipe)
		r.Put("/update/:id", binding.Bind(Recipe{}), UpdateRecipe)
		r.Delete("/delete/:id", DeleteRecipe)
	})

	m.Get("/foodGroup", func() []byte {
		foodGroupDB := session.DB("CNF").C("foodGroup")
		query := foodGroupDB.Find(nil)
		var result []d.FoodGroup
		query.All(&result)
		b, _ := json.Marshal(result)
		return b
	})

	m.Run()
}
示例#14
0
func (h *HTTPService) Start() {
	fmt.Println("Process Dispatcher Listening on Port : 5000")
	m := martini.Classic()
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"securityToken", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	m.Post("/:namespace/:class", handleRequest)

	m.RunOnAddr(":5000")
}
示例#15
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)
}
示例#16
0
func main() {
	server := martini.Classic()
	server.Use(martini.Static("../public"))
	server.Use(martini.Static("../assets/javascript/app"))
	server.Use(nocache.UpdateCacheHeaders())
	server.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"https://localhost:3000"},
		AllowMethods:     []string{"POST", "GET"},
		AllowHeaders:     []string{"Origin", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))
	server.Get("/")
	server.Post("/calculator", Calculate)

	log.Fatal(http.ListenAndServe(":3000", server))
}
示例#17
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 获取订阅列表
	m.Get("/feeds", func(params martini.Params, r render.Render) {
		username := params["username"]
		session := createSession()
		defer session.Close()
		c := session.DB("reader").C("users")
		user := User{}
		c.Find(bson.M{"name": username}).One(&user)
		r.JSON(200, user)
	})

	// 保存订阅列表
	m.Put("/feeds", func(params martini.Params, r render.Render) {
		session := createSession()
		defer session.Close()
		c := session.DB("reader").C("users")
		c.UpdateId(params["_id"], params)
		fmt.Printf(params["_id"])

		//添加new feed到Recourse
		//todo

		r.JSON(200, map[string]interface{}{"result": "ok"})
	})

	m.RunOnAddr(":31001")
	m.Run()

	//TODO
	//GET /feeds/items
	//POST /feeds/items/{id}/read
	//POST /feeds/items/{id}/star
	//POST /feeds/items/{id}/unstar
}
示例#18
0
文件: mtaapi.go 项目: jroblak/mtaapi
func main() {
	server := martini.Classic()

	server.Use(cors.Allow(&cors.Options{
		AllowOrigins:  []string{"*"},
		AllowMethods:  []string{"GET"},
		AllowHeaders:  []string{"Origin"},
		ExposeHeaders: []string{"Content-Length"},
	}))

	server.Get("/mta-api/subway", func() string {
		var buffer bytes.Buffer
		var r MTAResponse
		var bytes []byte

		resp, err := http.Get("http://www.mta.info/service_status_json/23458509")

		if err != nil {
			buffer.WriteString(err.Error())
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			buffer.WriteString(err.Error())
		}

		stringed := string(body[:])
		stringed = strings.Replace(stringed, "\\u0022", "\"", -1)
		stringed = stringed[3 : len(stringed)-1]

		bytes = []byte(stringed)

		e := json.Unmarshal(bytes, &r)
		if e != nil {
			buffer.WriteString(e.Error())
		}

		b, err := json.Marshal(r.Subway)

		return string(b[:])
	})
	server.Run()
}
示例#19
0
文件: voice.go 项目: is00hcw/gitwork
func initServer() {
	// addr := "localhost:7000"
	m := martini.Classic()
	/*
	  f, err := os.OpenFile("server.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			panic(err)
		}
		defer f.Close()
	  m.Map(stdlog.New(f, "[martini]", stdlog.LstdFlags))

	  m.Use(martini.Static(filepath.Join(binRoot, "assets/statics")))
		m.Use(render.Renderer(render.Options{
			Directory:  filepath.Join(binRoot, "assets/template"),
			Extensions: []string{".tmpl", ".html"},
			Charset:    "UTF-8",
			IndentJSON: true,
		})) */

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"POST", "GET", "DELETE", "PUT"},
		AllowHeaders:     []string{"Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: false,
	}))

	// m.Get("/sample/:addr", sample)
	m.Get("/", func() string {
		return "Hello world!"
	})

	m.Get("/voice", voiceHandler)

	/* m.Get("/", func(r render.Render) {
		r.Redirect("/admin")
	}) */

	// m.Run()
	//m.RunOnAddr(addr)
	m.RunOnAddr(":8000")
}
示例#20
0
func main() {
	switch {
	case h:
		flag.PrintDefaults()
	default:
		m := martini.Classic()

		m.Use(render.Renderer())

		m.Use(cors.Allow(&cors.Options{
			AllowOrigins: []string{"*"},
			AllowHeaders: []string{"Origin"},
		}))

		m.Get("/user/:id", GetUserLogs)
		m.Get("/repo/:name", GetRepoLogs)

		m.Run()
	}
}
示例#21
0
func main() {

	m := martini.Classic()
	m.Use(martini.Logger())

	// Add a redis repo to use
	m.MapTo(service.NewDeparturesService(), (*service.DeparturesService)(nil))
	m.MapTo(service.NewConfigService(), (*service.ConfigService)(nil))

	// Set cors to be enabled for all requests
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowCredentials: true,
	}))

	// set routes
	m.Get("/:station/departures", GetStationDepartures)
	m.Get("/config", GetConfig)

	m.Run()
}
示例#22
0
func (r *RestServer) Listen() error {

	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Map(r.RoomModel)
	m.Map(r.ThingModel)
	m.Map(r.DeviceModel)
	m.Map(r.SiteModel)
	m.Map(r.Conn)
	m.Map(r.StateManager)

	m.Use(func(c martini.Context) {
		conn := r.RedisPool.Get()
		c.Map(conn)

		c.Next()

		conn.Close()
	})

	location := NewLocationRouter()
	thing := NewThingRouter()
	room := NewRoomRouter()
	site := NewSiteRouter()

	m.Group("/rest/v1/locations", location.Register)
	m.Group("/rest/v1/things", thing.Register)
	m.Group("/rest/v1/rooms", room.Register)
	m.Group("/rest/v1/sites", site.Register)

	listenAddress := fmt.Sprintf(":%d", config.MustInt("homecloud.rest.port"))

	r.log.Infof("Listening at %s", listenAddress)

	return http.ListenAndServe(listenAddress, m)
}
示例#23
0
func App() *martini.ClassicMartini {
	m := martini.Classic()
	// m.Use(DB())
	m.Use(render.Renderer())

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*", "http://localhost:9000", "http://127.0.0.1:9000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	m.Group("/visitor", func(r martini.Router) {
		r.Get("/:id", Get)
		r.Get("", All)
		r.Post("/:id", Post)
		r.Put("/:id", Put)
	})

	return m
}
示例#24
0
文件: server.go 项目: ckeyer/go-ci
func Serve(listenAddr string) {
	m := NewMartini()
	view := views.New()

	m.NotFound(NotFound, view.ServeHTTP)

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "OPTIONS", "POST", "DELETE"},
		AllowHeaders:     []string{"Limt,Offset,Content-Type,Origin,Accept,Authorization"},
		ExposeHeaders:    []string{"Record-Count", "Limt", "Offset", "Content-Type"},
		AllowCredentials: true,
		MaxAge:           time.Second * 864000,
	}))

	m.Use(sessions.Sessions("sloth", utils.GetCookieStore()))
	m.Use(requestContext())

	m.Group(WEB_HOOKS, func(r martini.Router) {
		r.Post("/github", WMAuthGithubServer, GithubWebhooks)
	}, MWHello)

	m.Group(API_PREFIX, func(r martini.Router) {
		r.Get("/hello", Hello)
		r.Post("/login", Login)
	}, MWHello)

	logger := log.StandardLogger()
	server := &http.Server{
		Handler:  m,
		Addr:     listenAddr,
		ErrorLog: stdlog.New(logger.Writer(), "", 0),
	}

	log.Info("server is starting on ", listenAddr)
	if err := server.ListenAndServe(); err != nil {
		log.Error(err)
	}
}
示例#25
0
func App() *martini.ClassicMartini {
	m := martini.Classic()
	// Make a new Broker instance
	MembersBroker = NewBroker()
	m.Map(MembersBroker)

	m.Get("/", func() string {
		return "Sup"
	})
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{"POST", "OPTIONS"},
		AllowHeaders: []string{"Origin", "Content-type"},
	}))

	m.Post("/update/:room", UpdateHandler)
	m.Post("/failure", FailureHandler)

	m.Options("/update/:room", OptionsHandler)

	m.Get("/stream/:room", ClientStream)

	return m
}
示例#26
0
func main() {

	m := martini.New()
	route := martini.NewRouter()

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "PATCH"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// generated with "go-bindata -o ../../static.go public/..."
	// m.Use(staticbin.Static("public", Asset))

	mb := minibus.Init()

	payments := make([]Payment, 0)
	initialAmount := 513.22

	route.Get("/conn/:cust/:conn", func(res http.ResponseWriter, params martini.Params) {
		cust := params["cust"]
		conn := params["conn"]

		message, err := mb.Receive(cust, conn)
		if err != nil {
			fmt.Fprintln(res, "{}")
		} else {
			fmt.Fprintln(res, message.Contents)
		}
	})
	route.Post("/conn/:cust", func(res http.ResponseWriter, req *http.Request, params martini.Params) {
		cust := params["cust"]

		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			http.Error(res, "Unable to read request body: "+err.Error(), http.StatusInternalServerError)
			return
		}

		fmt.Println("Got: ", string(body))

		var incoming IncomingMessage
		err = json.Unmarshal(body, &incoming)
		if err != nil {
			http.Error(res, "Bad request: "+err.Error(), http.StatusBadRequest)
			return
		}

		if incoming.Type == "add-payment" {
			fmt.Println("Location : ", incoming.Args["location"])
			fmt.Println("Amount : ", incoming.Args["amount"])

			amount, _ := strconv.ParseFloat(incoming.Args["amount"], 64)

			payments = append(payments, Payment{incoming.Args["location"], amount})

			coredata := Data{
				initialAmount,
				payments,
			}

			json, _ := json.Marshal(coredata)

			fmt.Println(string(json))

			mb.Send(cust, string(json))
		} else if incoming.Type == "load-info" {
			coredata := Data{
				initialAmount,
				payments,
			}

			json, _ := json.Marshal(coredata)

			fmt.Println(string(json))

			mb.Send(cust, string(json))
		}
	})

	m.Action(route.Handle)

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

	m.Run()
}
示例#27
0
func runDashboard(addr string, httpLogFile string) {
	log.Info("dashboard listening on addr: ", addr)
	m := martini.Classic()
	f, err := os.OpenFile(httpLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		Fatal(err)
	}
	defer f.Close()

	m.Map(stdlog.New(f, "[martini]", stdlog.LstdFlags))
	binRoot, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		Fatal(err)
	}

	m.Use(martini.Static(filepath.Join(binRoot, "assets/statics")))
	m.Use(render.Renderer(render.Options{
		Directory:  filepath.Join(binRoot, "assets/template"),
		Extensions: []string{".tmpl", ".html"},
		Charset:    "UTF-8",
		IndentJSON: true,
	}))

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"POST", "GET", "DELETE", "PUT"},
		AllowHeaders:     []string{"Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: false,
	}))

	m.Get("/api/server_groups", apiGetServerGroupList)
	m.Get("/api/overview", apiOverview)

	m.Get("/api/redis/:addr/stat", apiRedisStat)
	m.Get("/api/redis/:addr/:id/slotinfo", apiGetRedisSlotInfo)
	m.Get("/api/redis/group/:group_id/:slot_id/slotinfo", apiGetRedisSlotInfoFromGroupId)

	m.Put("/api/server_groups", binding.Json(models.ServerGroup{}), apiAddServerGroup)
	m.Put("/api/server_group/(?P<id>[0-9]+)/addServer", binding.Json(models.Server{}), apiAddServerToGroup)
	m.Delete("/api/server_group/(?P<id>[0-9]+)", apiRemoveServerGroup)

	m.Put("/api/server_group/(?P<id>[0-9]+)/removeServer", binding.Json(models.Server{}), apiRemoveServerFromGroup)
	m.Get("/api/server_group/(?P<id>[0-9]+)", apiGetServerGroup)
	m.Post("/api/server_group/(?P<id>[0-9]+)/promote", binding.Json(models.Server{}), apiPromoteServer)

	m.Get("/api/migrate/status", apiMigrateStatus)
	m.Get("/api/migrate/tasks", apiGetMigrateTasks)
	m.Post("/api/migrate", binding.Json(migrateTaskForm{}), apiDoMigrate)

	m.Post("/api/rebalance", apiRebalance)

	m.Get("/api/slot/list", apiGetSlots)
	m.Get("/api/slot/:id", apiGetSingleSlot)
	m.Post("/api/slots/init", apiInitSlots)
	m.Get("/api/slots", apiGetSlots)
	m.Post("/api/slot", binding.Json(RangeSetTask{}), apiSlotRangeSet)
	m.Get("/api/proxy/list", apiGetProxyList)
	m.Get("/api/proxy/debug/vars", apiGetProxyDebugVars)
	m.Post("/api/proxy", binding.Json(models.ProxyInfo{}), apiSetProxyStatus)

	m.Get("/api/action/gc", apiActionGC)
	m.Get("/api/force_remove_locks", apiForceRemoveLocks)
	m.Get("/api/remove_fence", apiRemoveFence)

	m.Get("/slots", pageSlots)
	m.Get("/", func(r render.Render) {
		r.Redirect("/admin")
	})
	zkBuilder := utils.NewConnBuilder(globalEnv.NewZkConn)
	safeZkConn = zkBuilder.GetSafeConn()
	unsafeZkConn = zkBuilder.GetUnsafeConn()

	// create temp node in ZK
	if err := createDashboardNode(); err != nil {
		log.Fatal(err) // do not release dashborad node here
	}

	// create long live migrate manager
	globalMigrateManager = NewMigrateManager(safeZkConn, globalEnv.ProductName())

	go func() {
		c := getProxySpeedChan()
		for {
			atomic.StoreInt64(&proxiesSpeed, <-c)
		}
	}()

	m.RunOnAddr(addr)
}
示例#28
0
func main() {
	// TODO move to own handler
	// create a global App var to hold your app id and secret.
	globalApp := fb.New(os.Getenv("FACEBOOK_APP_ID"), os.Getenv("FACEBOOK_SECRET"))
	globalApp.RedirectUri = "http://localhost:3000/auth/facebook/callback" // TODO

	// https://developers.facebook.com/docs/graph-api/securing-requests
	globalApp.EnableAppsecretProof = true

	// instantiate Martini
	m := martini.Classic()
	m.Use(martini.Logger())

	// setup database
	dbmap = initDb()
	defer dbmap.Db.Close()

	// CORS
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"http://localhost:*"},
		AllowMethods:     []string{"GET", "POST"},
		AllowHeaders:     []string{"Origin", "Authorization", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// Authentication
	m.Use(func(c martini.Context, res http.ResponseWriter, req *http.Request) {
		accessToken := req.Header.Get("Authorization") // TODO expect "Bearer: {TOKEN}" format?
		session := globalApp.Session(accessToken)

		// TODO DELETE ME
		log.Printf("accessToken=%s", accessToken)

		// TODO make currentUser globally available
		// TODO add User struct and use res.Decode(&user)
		var user *User
		attrs, err := session.Get("/me", nil)

		if err != nil {
			// err can be an facebook API error.
			// if so, the Error struct contains error details.
			if e, ok := err.(*fb.Error); ok {
				log.Printf("Facebook error. [message:%v] [type:%v] [code:%v] [subcode:%v]", e.Message, e.Type, e.Code, e.ErrorSubcode)
			}

			res.WriteHeader(http.StatusUnauthorized)
		} else {
			user = findOrCreateUser(attrs)
			c.Map(user)
		}

		if user != nil {
			log.Printf("Logged in as: %s %s", user.FirstName, user.LastName)
		}
	})

	// Encoding
	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		// Use indentations. &pretty=1
		pretty, _ := strconv.ParseBool(r.FormValue("pretty"))
		// Use null instead of empty object for json &null=1
		null, _ := strconv.ParseBool(r.FormValue("null"))
		// JSON no matter what
		c.MapTo(encoder.JsonEncoder{PrettyPrint: pretty, PrintNull: null}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Get("/", func(user *User) string {
		// serve SPA ?
		return "Hello world" + user.FirstName
	})

	m.Get("/tells", func(enc encoder.Encoder, user *User) (int, []byte) {
		// get all tells for user and render JSON array
		tells := user.getTells()
		return http.StatusOK, encoder.Must(enc.Encode(tells))
	})

	m.Post("/tells", binding.Bind(Tell{}), func(enc encoder.Encoder, user *User, tell Tell) (int, []byte) {
		// create new tell for user
		tell = user.Tell(tell)
		return http.StatusOK, encoder.Must(enc.Encode(tell))
	})

	m.Run()
}
示例#29
0
文件: ks.go 项目: steveoc64/ksm
// Main function
func main() {
	log.Println("Kriegspiel Registration Server")

	initJWT()

	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins: []string{"*"},
	}))

	m.Use(DB())

	// Login request - either accept or fail
	m.Post("/login", binding.Bind(UserData{}), func(db *mgo.Database, user UserData) (int, string) {
		return login(db, user)
	})

	// Register new account
	m.Post("/register", binding.Bind(UserData{}), func(db *mgo.Database, user UserData) (int, string) {
		return registerUser(db, user)
	})
	// Update account details
	m.Post("/updateuser", binding.Bind(UpdateUserData{}), func(db *mgo.Database, user UpdateUserData) (int, string) {
		return updateUser(db, user)
	})
	// Get the user account details
	m.Post("/getuser", binding.Bind(TokenData{}), func(db *mgo.Database, token TokenData) (int, string) {
		return getUser(db, token)
	})

	// Forgot Password
	m.Post("/forgot", binding.Bind(UserData{}), func(db *mgo.Database, user UserData) (int, string) {
		return forgotPassword(db, user)
	})

	// Test Token
	m.Post("/token", binding.Bind(TokenData{}), func(db *mgo.Database, t TokenData) (int, string) {
		status, desc, _ := securityCheck(db, t.Token)
		return status, desc
	})

	// Save a map
	m.Post("/savemap", binding.Bind(MapSaveRequest{}), func(db *mgo.Database, mapReq MapSaveRequest) (int, string) {
		return saveMap(db, mapReq)
	})

	// Delete a map
	m.Post("/deletemap", binding.Bind(MapDeleteRequest{}), func(db *mgo.Database, mapDelReq MapDeleteRequest) (int, string) {
		return deleteMap(db, mapDelReq)
	})

	// Load a map
	m.Post("/loadmap", binding.Bind(MapLoadRequest{}), func(db *mgo.Database, mapReq MapLoadRequest) (int, string) {
		return loadMap(db, mapReq)
	})

	// Get a list of scenarios
	m.Post("/scenarios", binding.Bind(ScenarioListRequest{}), func(db *mgo.Database, slr ScenarioListRequest) (int, string) {
		return scenarioList(db, slr)
	})

	// Get a set of lookup values
	m.Post("/lookups", binding.Bind(LookupRequest{}), func(db *mgo.Database, l LookupRequest) (int, string) {
		return lookups(db, l)
	})

	// Get a set of forces for the given period
	m.Post("/forces", binding.Bind(ForcesRequest{}), func(db *mgo.Database, f ForcesRequest) (int, string) {
		return getForces(db, f)
	})

	// Validate an account
	m.Get("/validate/:key", func(db *mgo.Database, params martini.Params) (int, string) {
		retval, resultStr := validateUser(db, params)
		if retval >= http.StatusBadRequest {
			log.Println("Error Validating User:"******"Validated ", resultStr)
			return retval, "Thanks " + resultStr + ", your account has now been validated, and you can start playing !!"
		}
	})
	m.Use(martini.Static("app"))
	m.RunOnAddr(":8231")
}
示例#30
0
文件: index.go 项目: ninnemana/API
/**
 * All GET routes require either public or private api keys to be passed in.
 *
 * All POST routes require private api keys to be passed in.
 */
func main() {
	flag.Parse()

	m := martini.Classic()
	// gorelic.InitNewrelicAgent("5fbc49f51bd658d47b4d5517f7a9cb407099c08c", "API", false)
	// m.Use(gorelic.Handler)
	// m.Use(gzip.All())
	m.Use(middleware.Meddler())
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Content-Type", "Accept", "Access-Control-Allow-Origin", "Authorization"},
		ExposeHeaders:    []string{"Content-Type", "Accept", "Access-Control-Allow-Origin", "Authorization"},
		AllowCredentials: false,
	}))

	store := sessions.NewCookieStore([]byte("api_secret_session"))
	m.Use(sessions.Sessions("api_sessions", store))
	m.Use(encoding.MapEncoder)

	m.Group("/apiKeyTypes", func(r martini.Router) {
		r.Get("", apiKeyType.GetApiKeyTypes)
	})

	m.Group("/applicationGuide", func(r martini.Router) {
		r.Get("/website/:id", applicationGuide.GetApplicationGuidesByWebsite)
		r.Get("/:id", applicationGuide.GetApplicationGuide)
		r.Delete("/:id", applicationGuide.DeleteApplicationGuide)
		r.Post("", applicationGuide.CreateApplicationGuide)
	})

	m.Group("/blogs", func(r martini.Router) {
		r.Get("", blog_controller.GetAll)                      //sort on any field e.g. ?sort=Name&direction=descending
		r.Get("/categories", blog_controller.GetAllCategories) //all categories; sort on any field e.g. ?sort=Name&direction=descending
		r.Get("/category/:id", blog_controller.GetBlogCategory)
		r.Get("/search", blog_controller.Search) //search field = value e.g. /blogs/search?key=8AEE0620-412E-47FC-900A-947820EA1C1D&slug=cyclo
		r.Post("/categories", blog_controller.CreateBlogCategory)
		r.Delete("/categories/:id", blog_controller.DeleteBlogCategory)
		r.Get("/:id", blog_controller.GetBlog)       //get blog by {id}
		r.Put("/:id", blog_controller.UpdateBlog)    //create {post_title ,slug ,post_text, createdDate, publishedDate, lastModified, userID, meta_title, meta_description, keywords, active} returns new id
		r.Post("", blog_controller.CreateBlog)       //update {post_title ,slug ,post_text, createdDate, publishedDate, lastModified, userID, meta_title, meta_description, keywords, active} required{id}
		r.Delete("/:id", blog_controller.DeleteBlog) //{?id=id}
		r.Delete("", blog_controller.DeleteBlog)     //{id}
	})

	m.Group("/brands", func(r martini.Router) {
		r.Get("", brand_ctlr.GetAllBrands)
		r.Post("", brand_ctlr.CreateBrand)
		r.Get("/:id", brand_ctlr.GetBrand)
		r.Put("/:id", brand_ctlr.UpdateBrand)
		r.Delete("/:id", brand_ctlr.DeleteBrand)
	})

	m.Group("/category", func(r martini.Router) {
		r.Get("/:id/parts", category_ctlr.GetCategoryParts)
		r.Get("/:id", category_ctlr.GetCategory)
		r.Get("", category_ctlr.GetCategoryTree)
	})

	m.Group("/contact", func(r martini.Router) {
		m.Group("/types", func(r martini.Router) {
			r.Get("/receivers/:id", contact.GetReceiversByContactType)
			r.Get("", contact.GetAllContactTypes)
			r.Get("/:id", contact.GetContactType)
			r.Post("", contact.AddContactType)
			r.Put("/:id", contact.UpdateContactType)
			r.Delete("/:id", contact.DeleteContactType)
		})
		m.Group("/receivers", func(r martini.Router) {
			r.Get("", contact.GetAllContactReceivers)
			r.Get("/:id", contact.GetContactReceiver)
			r.Post("", contact.AddContactReceiver)
			r.Put("/:id", contact.UpdateContactReceiver)
			r.Delete("/:id", contact.DeleteContactReceiver)
		})
		// r.Post("/sendmail/:id", contact.SendEmail)
		r.Get("", contact.GetAllContacts)
		r.Get("/:id", contact.GetContact)
		r.Post("/:contactTypeID", contact.AddDealerContact)
		r.Put("/:id", contact.UpdateContact)
		r.Delete("/:id", contact.DeleteContact)
	})

	m.Group("/shopify/customers", func(r martini.Router) {
		// Customers - shop endpoints
		r.Get("", cart_ctlr.GetCustomers)
		r.Post("", cart_ctlr.AddCustomer)
		r.Get("/search", cart_ctlr.SearchCustomer)
		r.Get("/:id", cart_ctlr.GetCustomer)
		r.Put("/:id", cart_ctlr.EditCustomer)
		r.Delete("/:id", cart_ctlr.DeleteCustomer)
		r.Get("/:id/orders", cart_ctlr.GetCustomerOrders)

		// Addresses
		r.Get("/:id/addresses", cart_ctlr.GetAddresses)
		r.Get("/:id/addresses/:address", cart_ctlr.GetAddress)
		r.Post("/:id/addresses", cart_ctlr.AddAddress)
		r.Put("/:id/addresses/:address/default", cart_ctlr.SetDefaultAddress)
		r.Put("/:id/addresses/:address", cart_ctlr.EditAddress)
		r.Delete("/:id/addresses/:address", cart_ctlr.DeleteAddress)

	})

	m.Group("/shopify/order", func(r martini.Router) {
		// Orders
		r.Post("/order", cart_ctlr.CreateOrder)
	})

	m.Group("/shopify/account", func(r martini.Router) {
		// Account - user endpoints
		r.Get("", cart_ctlr.GetAccount)
		r.Post("", cart_ctlr.AddAccount)
		r.Put("", cart_ctlr.EditAccount)
		r.Post("/login", cart_ctlr.AccountLogin)

		// m.Group("/shopify/account/address", func(r martini.Router) {
		// 	r.Get("", cart_ctlr.GetAccountAddresses)
		// 	r.Post("", cart_ctlr.AddAccountAddress)
		// 	r.Put("", cart_ctlr.EditAccountAddress)
		// 	r.Delete("", cart_ctlr.DeleteAccountAddress)
		// })

	})

	m.Group("/cartIntegration", func(r martini.Router) {
		r.Get("/part/:part", cartIntegration.GetPartPricesByPartID)
		r.Get("/part", cartIntegration.GetAllPartPrices)
		r.Get("/count", cartIntegration.GetPricingCount)
		r.Get("", cartIntegration.GetPricing)
		r.Get("/:page/:count", cartIntegration.GetPricingPaged)
		r.Post("/part", cartIntegration.CreatePrice)
		r.Put("/part", cartIntegration.UpdatePrice)
		r.Get("/priceTypes", cartIntegration.GetAllPriceTypes)

		r.Post("/resetToMap", cartIntegration.ResetAllToMap)
		r.Post("/global/:type/:percentage", cartIntegration.Global)

		r.Post("/upload", cartIntegration.Upload)
		r.Post("/download", cartIntegration.Download)

	})

	m.Group("/cache", func(r martini.Router) { // different endpoint because partial matching matches this to another excused route
		r.Get("/key", cache.GetByKey)
		r.Get("/keys", cache.GetKeys)
		r.Delete("/keys", cache.DeleteKey)
	})

	m.Group("/cust", func(r martini.Router) { // different endpoint because partial matching matches this to another excused route
		r.Post("/user/changePassword", customer_ctlr.ChangePassword)
	})

	m.Group("/cache", func(r martini.Router) { // different endpoint because partial matching matches this to another excused route
		r.Get("/key", cache.GetByKey)
		r.Get("/keys", cache.GetKeys)
		r.Delete("/keys", cache.DeleteKey)
	})

	m.Group("/customer", func(r martini.Router) {
		r.Get("", customer_ctlr.GetCustomer)
		r.Post("", customer_ctlr.GetCustomer)

		r.Post("/auth", customer_ctlr.AuthenticateUser)
		r.Get("/auth", customer_ctlr.KeyedUserAuthentication)
		r.Post("/user/changePassword", customer_ctlr.ChangePassword)
		r.Post("/user", customer_ctlr.GetUser)
		r.Post("/user/register", customer_ctlr.RegisterUser)
		r.Post("/user/resetPassword", customer_ctlr.ResetPassword)
		r.Delete("/deleteKey", customer_ctlr.DeleteUserApiKey)
		r.Post("/generateKey/user/:id/key/:type", customer_ctlr.GenerateApiKey)
		r.Get("/user/:id", customer_ctlr.GetUserById)
		r.Post("/user/:id", customer_ctlr.UpdateCustomerUser)
		r.Delete("/user/:id", customer_ctlr.DeleteCustomerUser)
		r.Any("/users", customer_ctlr.GetUsers)

		r.Delete("/allUsersByCustomerID/:id", customer_ctlr.DeleteCustomerUsersByCustomerID) //Takes CustomerID (UUID)---danger!

		r.Put("/location/json", customer_ctlr.SaveLocationJson)
		r.Put("/location/json/:id", customer_ctlr.SaveLocationJson)
		r.Post("/location", customer_ctlr.SaveLocation)
		r.Get("/location/:id", customer_ctlr.GetLocation)
		r.Put("/location/:id", customer_ctlr.SaveLocation)
		r.Delete("/location/:id", customer_ctlr.DeleteLocation)

		r.Get("/locations", customer_ctlr.GetLocations)
		r.Post("/locations", customer_ctlr.GetLocations)

		r.Get("/price/:id", customer_ctlr.GetCustomerPrice)           //{part id}
		r.Get("/cartRef/:id", customer_ctlr.GetCustomerCartReference) //{part id}

		// Customer CMS endpoints
		// All Customer Contents
		r.Get("/cms", customer_ctlr.GetAllContent)
		// Content Types
		r.Get("/cms/content_types", customer_ctlr.GetAllContentTypes)

		// Customer Part Content
		r.Get("/cms/part", customer_ctlr.AllPartContent)
		r.Get("/cms/part/:id", customer_ctlr.UniquePartContent)
		r.Put("/cms/part/:id", customer_ctlr.UpdatePartContent) //partId
		r.Post("/cms/part/:id", customer_ctlr.CreatePartContent)
		r.Delete("/cms/part/:id", customer_ctlr.DeletePartContent)

		// Customer Category Content
		r.Get("/cms/category", customer_ctlr.AllCategoryContent)
		r.Get("/cms/category/:id", customer_ctlr.UniqueCategoryContent)
		r.Post("/cms/category/:id", customer_ctlr.UpdateCategoryContent) //categoryId
		r.Delete("/cms/category/:id", customer_ctlr.DeleteCategoryContent)

		// Customer Content By Content Id
		r.Get("/cms/:id", customer_ctlr.GetContentById)
		r.Get("/cms/:id/revisions", customer_ctlr.GetContentRevisionsById)

		//Customer prices
		r.Get("/prices/part/:id", customer_ctlr.GetPricesByPart)         //{id}; id refers to partId
		r.Post("/prices/sale", customer_ctlr.GetSales)                   //{start}{end}{id} -all required params; id refers to customerId
		r.Get("/prices/:id", customer_ctlr.GetPrice)                     //{id}; id refers to {id} refers to customerPriceId
		r.Get("/prices", customer_ctlr.GetAllPrices)                     //returns all {sort=field&direction=dir}
		r.Put("/prices/:id", customer_ctlr.CreateUpdatePrice)            //updates when an id is present; otherwise, creates; {id} refers to customerPriceId
		r.Post("/prices", customer_ctlr.CreateUpdatePrice)               //updates when an id is present; otherwise, creates; {id} refers to customerPriceId
		r.Delete("/prices/:id", customer_ctlr.DeletePrice)               //{id} refers to customerPriceId
		r.Get("/pricesByCustomer/:id", customer_ctlr.GetPriceByCustomer) //{id} refers to customerId; returns CustomerPrices

		r.Post("/:id", customer_ctlr.SaveCustomer)
		r.Delete("/:id", customer_ctlr.DeleteCustomer)
		r.Put("", customer_ctlr.SaveCustomer)
	})

	m.Group("/dealers", func(r martini.Router) {
		r.Get("/business/classes", dealers_ctlr.GetAllBusinessClasses)
		r.Get("/etailer", dealers_ctlr.GetEtailers)
		r.Get("/local", dealers_ctlr.GetLocalDealers)
		r.Get("/local/regions", dealers_ctlr.GetLocalRegions)
		r.Get("/local/tiers", dealers_ctlr.GetLocalDealerTiers)
		r.Get("/local/types", dealers_ctlr.GetLocalDealerTypes)
		r.Get("/etailer/platinum", dealers_ctlr.PlatinumEtailers)
		r.Get("/location/:id", dealers_ctlr.GetLocationById)
		r.Get("/search/:search", dealers_ctlr.SearchLocations)
		r.Get("/search/type/:search", dealers_ctlr.SearchLocationsByType)
		r.Get("/search/geo/:latitude/:longitude", dealers_ctlr.SearchLocationsByLatLng)
	})

	m.Group("/faqs", func(r martini.Router) {
		r.Get("", faq_controller.GetAll)          //get all faqs; takes optional sort param {sort=true} to sort by question
		r.Get("/search", faq_controller.Search)   //takes {question, answer, page, results} - all parameters are optional
		r.Get("/(:id)", faq_controller.Get)       //get by id {id}
		r.Post("", faq_controller.Create)         //takes {question, answer}; returns object with new ID
		r.Put("/(:id)", faq_controller.Update)    //{id, question and/or answer}
		r.Delete("/(:id)", faq_controller.Delete) //{id}
		r.Delete("", faq_controller.Delete)       //{?id=id}
	})

	m.Group("/forum", func(r martini.Router) {
		//groups
		r.Get("/groups", forum_ctlr.GetAllGroups)
		r.Get("/groups/:id", forum_ctlr.GetGroup)
		r.Post("/groups", forum_ctlr.AddGroup)
		r.Put("/groups/:id", forum_ctlr.UpdateGroup)
		r.Delete("/groups/:id", forum_ctlr.DeleteGroup)
		//topics
		r.Get("/topics", forum_ctlr.GetAllTopics)
		r.Get("/topics/:id", forum_ctlr.GetTopic)
		r.Post("/topics", forum_ctlr.AddTopic)
		r.Put("/topics/:id", forum_ctlr.UpdateTopic)
		r.Delete("/topics/:id", forum_ctlr.DeleteTopic)
		//threads
		r.Get("/threads", forum_ctlr.GetAllThreads)
		r.Get("/threads/:id", forum_ctlr.GetThread)
		r.Delete("/threads/:id", forum_ctlr.DeleteThread)
		//posts
		r.Get("/posts", forum_ctlr.GetAllPosts)
		r.Get("/posts/:id", forum_ctlr.GetPost)
		r.Post("/posts", forum_ctlr.AddPost)
		r.Put("/posts/:id", forum_ctlr.UpdatePost)
		r.Delete("/posts/:id", forum_ctlr.DeletePost)
	})

	m.Group("/geography", func(r martini.Router) {
		r.Get("/states", geography.GetAllStates)
		r.Get("/countries", geography.GetAllCountries)
		r.Get("/countrystates", geography.GetAllCountriesAndStates)
	})

	m.Group("/news", func(r martini.Router) {
		r.Get("", news_controller.GetAll)           //get all news; takes optional sort param {sort=title||lead||content||startDate||endDate||active||slug} to sort by question
		r.Get("/titles", news_controller.GetTitles) //get titles!{page, results} - all parameters are optional
		r.Get("/leads", news_controller.GetLeads)   //get leads!{page, results} - all parameters are optional
		r.Get("/search", news_controller.Search)    //takes {title, lead, content, publishStart, publishEnd, active, slug, page, results, page, results} - all parameters are optional
		r.Get("/:id", news_controller.Get)          //get by id {id}
		r.Post("", news_controller.Create)          //takes {question, answer}; returns object with new ID
		r.Post("/:id", news_controller.Update)      //{id, question and/or answer}
		r.Delete("/:id", news_controller.Delete)    //{id}
		r.Delete("", news_controller.Delete)        //{id}
	})

	m.Group("/part", func(r martini.Router) {
		r.Get("/featured", part_ctlr.Featured)
		r.Get("/latest", part_ctlr.Latest)
		r.Get("/:part/vehicles", part_ctlr.Vehicles)
		r.Get("/:part/attributes", part_ctlr.Attributes)
		r.Get("/:part/reviews", part_ctlr.ActiveApprovedReviews)
		r.Get("/:part/categories", part_ctlr.Categories)
		r.Get("/:part/content", part_ctlr.GetContent)
		r.Get("/:part/images", part_ctlr.Images)
		r.Get("/:part((.*?)\\.(PDF|pdf)$)", part_ctlr.InstallSheet)
		r.Get("/:part/packages", part_ctlr.Packaging)
		r.Get("/:part/pricing", part_ctlr.Prices)
		r.Get("/:part/related", part_ctlr.GetRelated)
		r.Get("/:part/videos", part_ctlr.Videos)
		r.Get("/:part/:year/:make/:model", part_ctlr.GetWithVehicle)
		r.Get("/:part/:year/:make/:model/:submodel", part_ctlr.GetWithVehicle)
		r.Get("/:part/:year/:make/:model/:submodel/:config(.+)", part_ctlr.GetWithVehicle)
		r.Get("/id/:part", part_ctlr.Get)
		r.Get("/identifiers", part_ctlr.Identifiers)
		r.Get("/:part", part_ctlr.PartNumber)
		r.Get("", part_ctlr.All)
	})

	m.Group("/salesrep", func(r martini.Router) {
		r.Get("", salesrep.GetAllSalesReps)
		r.Post("", salesrep.AddSalesRep)
		r.Get("/:id", salesrep.GetSalesRep)
		r.Put("/:id", salesrep.UpdateSalesRep)
		r.Delete("/:id", salesrep.DeleteSalesRep)
	})

	m.Get("/search/:term", search_ctlr.Search)

	m.Group("/site", func(r martini.Router) {
		m.Group("/menu", func(r martini.Router) {
			r.Get("/all", site.GetAllMenus)
			r.Get("/:id", site.GetMenu)                      //may pass id (int) or name(string)
			r.Get("/contents/:id", site.GetMenuWithContents) //may pass id (int) or name(string)
			r.Post("", site.SaveMenu)
			r.Put("/:id", site.SaveMenu)
			r.Delete("/:id", site.DeleteMenu)
		})
		m.Group("/content", func(r martini.Router) {
			r.Get("/all", site.GetAllContents)
			r.Get("/:id", site.GetContent) //may pass id (int) or slug(string)
			r.Get("/:id/revisions", site.GetContentRevisions)
			r.Post("", site.SaveContent)
			r.Put("/:id", site.SaveContent)
			r.Delete("/:id", site.DeleteContent)
		})
		r.Get("/details/:id", site.GetSiteDetails)
		r.Post("", site.SaveSite)
		r.Put("/:id", site.SaveSite)
		r.Delete("/:id", site.DeleteSite)
	})

	m.Group("/lp", func(r martini.Router) {
		r.Get("/:id", landingPage.Get)
	})
	m.Group("/showcase", func(r martini.Router) {
		r.Get("", showcase.GetAllShowcases)
		r.Get("/:id", showcase.GetShowcase)
		r.Post("", showcase.Save)
		// r.Put("/:id", showcase.Save)
		// r.Delete("/:id", showcase.Delete)
	})

	m.Group("/techSupport", func(r martini.Router) {
		r.Get("/all", techSupport.GetAllTechSupport)
		r.Get("/contact/:id", techSupport.GetTechSupportByContact)
		r.Get("/:id", techSupport.GetTechSupport)
		r.Post("/:contactReceiverTypeID/:sendEmail", techSupport.CreateTechSupport) //contactType determines who receives the email/sendEmail is a bool indicating if email should be sent
		r.Delete("/:id", techSupport.DeleteTechSupport)
	})

	m.Group("/testimonials", func(r martini.Router) {
		r.Get("", testimonials.GetAllTestimonials)
		r.Get("/:id", testimonials.GetTestimonial)
		r.Post("", testimonials.Save)
		r.Put("/:id", testimonials.Save)
		r.Delete("/:id", testimonials.Delete)
	})

	m.Group("/warranty", func(r martini.Router) {
		r.Get("/all", warranty.GetAllWarranties)
		r.Get("/contact/:id", warranty.GetWarrantyByContact)
		r.Get("/:id", warranty.GetWarranty)
		r.Post("/:contactReceiverTypeID/:sendEmail", warranty.CreateWarranty) //contactType determines who receives the email/sendEmail is a bool indicating if email should be sent
		r.Delete("/:id", warranty.DeleteWarranty)
	})

	m.Group("/webProperties", func(r martini.Router) {
		r.Post("/json/type", webProperty_controller.CreateUpdateWebPropertyType)
		r.Post("/json/type/:id", webProperty_controller.CreateUpdateWebPropertyType)
		r.Post("/json/requirement", webProperty_controller.CreateUpdateWebPropertyRequirement)
		r.Post("/json/requirement/:id", webProperty_controller.CreateUpdateWebPropertyRequirement)
		r.Post("/json/note", webProperty_controller.CreateUpdateWebPropertyNote)
		r.Post("/json/note/:id", webProperty_controller.CreateUpdateWebPropertyNote)
		r.Post("/json/:id", webProperty_controller.CreateUpdateWebProperty)
		r.Put("/json", webProperty_controller.CreateUpdateWebProperty)
		r.Post("/note/:id", webProperty_controller.CreateUpdateWebPropertyNote)               //updates when an id is present; otherwise, creates
		r.Put("/note", webProperty_controller.CreateUpdateWebPropertyNote)                    //updates when an id is present; otherwise, creates
		r.Delete("/note/:id", webProperty_controller.DeleteWebPropertyNote)                   //{id}
		r.Get("/note/:id", webProperty_controller.GetWebPropertyNote)                         //{id}
		r.Post("/type/:id", webProperty_controller.CreateUpdateWebPropertyType)               //updates when an id is present; otherwise, creates
		r.Put("/type", webProperty_controller.CreateUpdateWebPropertyType)                    //updates when an id is present; otherwise, creates
		r.Delete("/type/:id", webProperty_controller.DeleteWebPropertyType)                   //{id}
		r.Get("/type/:id", webProperty_controller.GetWebPropertyType)                         //{id}
		r.Post("/requirement/:id", webProperty_controller.CreateUpdateWebPropertyRequirement) //updates when an id is present; otherwise, creates
		r.Put("/requirement", webProperty_controller.CreateUpdateWebPropertyRequirement)      //updates when an id is present; otherwise, creates
		r.Delete("/requirement/:id", webProperty_controller.DeleteWebPropertyRequirement)     //{id}
		r.Get("/requirement/:id", webProperty_controller.GetWebPropertyRequirement)           //{id}
		r.Get("/search", webProperty_controller.Search)
		r.Get("/type", webProperty_controller.GetAllTypes)
		r.Get("/note", webProperty_controller.GetAllNotes)
		r.Get("/requirement", webProperty_controller.GetAllRequirements)
		r.Get("/customer", webProperty_controller.GetByPrivateKey)
		r.Get("", webProperty_controller.GetAll)
		r.Get("/:id", webProperty_controller.Get)                      //?id=id
		r.Delete("/:id", webProperty_controller.DeleteWebProperty)     //{id}
		r.Post("/:id", webProperty_controller.CreateUpdateWebProperty) //
		r.Put("", webProperty_controller.CreateUpdateWebProperty)      //can create notes(text) and requirements (requirement, by requirement=requirementID) while creating a property
	})

	// ARIES Year/Make/Model/Style
	m.Post("/vehicle", vehicle.Query)
	m.Post("/findVehicle", vehicle.GetVehicle)
	m.Post("/vehicle/inquire", vehicle.Inquire)
	m.Get("/vehicle/mongo/cols", vehicle.Collections)
	m.Post("/vehicle/mongo/apps", vehicle.ByCategory)
	m.Post("/vehicle/mongo/allCollections/category", vehicle.AllCollectionsLookupCategory)
	m.Post("/vehicle/mongo/allCollections", vehicle.AllCollectionsLookup)
	m.Post("/vehicle/mongo", vehicle.Lookup)
	m.Post("/vehicle/mongo/import", vehicle.ImportCsv)
	m.Get("/vehicle/mongo/all/:collection", vehicle.GetAllCollectionApplications)
	m.Put("/vehicle/mongo/:collection", vehicle.UpdateApplication)
	m.Delete("/vehicle/mongo/:collection", vehicle.DeleteApplication)
	m.Post("/vehicle/mongo/:collection", vehicle.CreateApplication)

	// CURT Year/Make/Model/Style
	m.Post("/vehicle/curt", vehicle.CurtLookup)

	m.Group("/videos", func(r martini.Router) {
		r.Get("/distinct", videos_ctlr.DistinctVideos) //old "videos" table - curtmfg?
		r.Get("/channel/type", videos_ctlr.GetAllChannelTypes)
		r.Get("/channel/type/:id", videos_ctlr.GetChannelType)
		r.Get("/channel", videos_ctlr.GetAllChannels)
		r.Get("/channels", videos_ctlr.GetAllChannels)
		r.Get("/channel/:id", videos_ctlr.GetChannel)
		r.Get("/cdn/type", videos_ctlr.GetAllCdnTypes)
		r.Get("/cdn/type/:id", videos_ctlr.GetCdnType)
		r.Get("/cdn", videos_ctlr.GetAllCdns)
		r.Get("/cdn/:id", videos_ctlr.GetCdn)
		r.Get("/type", videos_ctlr.GetAllVideoTypes)
		r.Get("/type/:id", videos_ctlr.GetVideoType)
		r.Get("", videos_ctlr.GetAllVideos)
		r.Get("/details/:id", videos_ctlr.GetVideoDetails)
		r.Get("/:id", videos_ctlr.Get)
	})

	m.Group("/vin", func(r martini.Router) {
		//option 1 - two calls - ultimately returns parts
		r.Get("/configs/:vin", vinLookup.GetConfigs)                    //returns vehicles - user must call vin/vehicle with vehicleID to get parts
		r.Get("/vehicleID/:vehicleID", vinLookup.GetPartsFromVehicleID) //returns an array of parts

		//option 2 - one call - returns vehicles with parts
		r.Get("/:vin", vinLookup.GetParts) //returns vehicles + configs with associates parts -or- an array of parts if only one vehicle config matches
	})

	m.Get("/status", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		w.Write([]byte("running"))
	})

	m.Get("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "http://labs.curtmfg.com/", http.StatusFound)
	})

	srv := &http.Server{
		Addr:         *listenAddr,
		Handler:      m,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
	}

	log.Printf("Starting server on 127.0.0.1%s\n", *listenAddr)
	log.Fatal(srv.ListenAndServe())
}