Beispiel #1
0
func main() {
	// Load DB
	options := &bolt.Options{Timeout: 2 * time.Second}
	dbPath := path.Join(os.Getenv("BOLT_PATH"), "reminder.db")
	db, err := bolt.Open(dbPath, 0600, options)
	if err != nil {
		log.Fatalf("Error opening bolt DB: %v", err)
	}
	defer db.Close()

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

	runningReminders.Schedule(db, rems)

	//
	// Router, etc
	//

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

	m.Map(db)

	r.Post("/sms", incomingSMS)

	m.Run()
}
Beispiel #2
0
func main() {
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(nrscstatic.NrscStatic("public", true))
	http.ListenAndServe(":8080", m)
}
Beispiel #3
0
// NewServer creates an instance of a martini server. The
// adapterInst parameter is the adapter type the server will
// use when dispatching requests.
func NewServer(adapterInst PanamaxAdapter) AdapterServer {
	s := martini.New()

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

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

	return &server
}
Beispiel #4
0
func (srv *httpServer) setupMiddleware() {
	srv.m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
	}))
	srv.m.Use(martini.Logger())
	srv.m.Use(CORSAllowAny())
}
Beispiel #5
0
func AppServer() *Server {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Use(DB())

	m.Action(r.Handle)
	return &Server{m, r}
}
Beispiel #6
0
func main() {
	// runtime.GOMAXPROCS(runtime.NumCPU())
	// fmt.Printf("GOMAXPROCS is %d\n", runtime.GOMAXPROCS(0))

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

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

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

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

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

		responses := httpFetch(urls, maxtime)

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

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

	if err := http.ListenAndServe(ADDR, m); err != nil {
		log.Fatal(err)
	}
}
Beispiel #7
0
// StatsServerMain is the whole shebang for the stats, mannn
func StatsServerMain(cfg *Config) {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(martini.Logger())
	m.Use(CORSAllowAny())

	m.Get(`/timeline/:id`, handleStatsJSONP)

	log.Printf("hustle Stats HTTP listening at %s\n", cfg.StatsAddr)
	log.Fatal(http.ListenAndServe(cfg.StatsAddr, m))
}
Beispiel #8
0
func createMartini(dbh *db.DBHandle) *martini.Martini {
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(
		render.Renderer(
			render.Options{
				IndentJSON: true,
			},
		),
	)

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

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

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

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

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

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

	m.Action(r.Handle)

	return m
}
func init() {
	m = martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("Strict-Transport-Security", "max-age=60000")
	})
	m.Use(martini.Static("public"))
	m.Use(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})
	r := martini.NewRouter()
	r.Put("/candidates", mainHandler)
	m.Action(r.Handle)
	http.Handle("/", m)
}
Beispiel #10
0
func main() {

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

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

	r := martini.NewRouter()
	r.Get("/ok", ok)
	r.Get("/panic", panicFunc)
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	http.ListenAndServe(":1810", m)
	// STOP OMIT
}
Beispiel #11
0
func makeService(ts tuplespace.RawTupleSpace, debug bool) *martini.Martini {
	m := martini.New()
	m.Use(martini.Recovery())
	if debug {
		m.Use(martini.Logger())
	}
	m.Use(server.SerializationMiddleware())

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

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

	m.Action(r.Handle)
	return m
}
Beispiel #12
0
func init() {
	m := martini.Classic()
	m.Use(appEngine)
	m.Use(martini.Logger())
	m.Get("/", func(c context.Context, res http.ResponseWriter) {
		players, err := getAllPlayers(c, 200)
		if err != nil {
			log.Errorf(c, "Can't load players from DS: %v", err)
		}
		tmplt.Execute(res, players)
	})

	m.Get("/players.json", func(c context.Context, w http.ResponseWriter) {
		w.Header().Add("Access-Control-Allow-Origin", "*")
		if players, err := getAllPlayers(c, 20); err != nil {
			log.Errorf(c, "Can't load players from DS: %v", err)
		} else {
			if b, err := json.Marshal(players); err != nil {
				log.Errorf(c, "Can't convert players to json: %v", err)
			} else {
				w.Write(b)
				return
			}
		}
		w.WriteHeader(404)
	})
	m.Get("/results.json", func(c context.Context, w http.ResponseWriter) {
		w.Header().Add("Access-Control-Allow-Origin", "*")
		if players, err := getAllResults(c); err != nil {
			log.Errorf(c, "Can't load results from DS: %v", err)
		} else {
			if b, err := json.Marshal(players); err != nil {
				log.Errorf(c, "Can't convert results to json: %v", err)
			} else {
				w.Write(b)
				return
			}
		}
		w.WriteHeader(404)
	})
	m.Post("/", binding.Bind(PlayerInfo{}), handlePlayer)

	http.Handle("/", m)
}
Beispiel #13
0
func init() {
	m = martini.New()
	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(auth.Basic(AuthToken, ""))
	m.Use(MapEncoder)
	// Setup routes
	r := martini.NewRouter()
	r.Get(`/albums`, GetAlbums)
	r.Get(`/albums/:id`, GetAlbum)
	r.Post(`/albums`, AddAlbum)
	r.Put(`/albums/:id`, UpdateAlbum)
	r.Delete(`/albums/:id`, DeleteAlbum)
	// Inject database
	m.MapTo(db, (*DB)(nil))
	// Add the router action
	m.Action(r.Handle)
}
func main() {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(martini.Logger())

	m.Get("/", func() string {
		return "<h1>Receipt Printer</h1>"
	})

	m.Get("/cache/clear", func(res render.Render, w http.ResponseWriter) {
		os.RemoveAll(filepath.Join("./tmp/"))
		w.Header().Set("Access-Control-Allow-Origin", "*")
		res.JSON(200, map[string]interface{}{"success": true})
	})

	m.Get("/print", printDocument)

	m.Get("/cancel/all", cancelAll)

	m.Get("/self_update", func(res render.Render, w http.ResponseWriter) {
		cmd := exec.Command("./update")
		cmd.Run()
		w.Header().Set("Access-Control-Allow-Origin", "*")
		res.JSON(200, map[string]interface{}{"success": true, "version": version})
	})

	m.Get("/status", func(res render.Render, w http.ResponseWriter) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		res.JSON(200, map[string]interface{}{"success": true, "version": version})
	})

	go func() {
		if err := http.ListenAndServe(":9632", m); err != nil {
			log.Fatal(err)
		}
	}()

	if err := http.ListenAndServeTLS(":9631", "cert.pem", "key.pem", m); err != nil {
		log.Fatal(err)
	}

	m.Run()
}
func init() {
	m = martini.New()

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

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

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

	// wireup router action
	m.Action(r.Handle)
}
Beispiel #16
0
func setupMartini() *martini.Martini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Static("assets", martini.StaticOptions{SkipLogging: true})) // skip logging on static content
	m.Use(martini.Logger())
	m.Use(render.Renderer(render.Options{
		Directory:  "templates",
		Layout:     "layout",
		Extensions: []string{".html"},
		Delims:     render.Delims{"{[{", "}]}"},
		IndentJSON: true,
	}))
	m.Use(ConfigOptions(configFile))
	m.Use(TaskList())
	m.Map(log.New(os.Stdout, logPrefix, logFlags))
	m.Action(r.Handle)

	setupRoutes(r)

	return m
}
func init() {
	m = martini.New()

	envEnvironment := os.Getenv("ENVIRONMENT")

	if envEnvironment == "" {
		envEnvironment = "development"
	}

	brokerConfig, _ = config.ParseFromYAMLFile(envEnvironment, "config/config.yml")
	b, _ = sqlbroker.New(brokerConfig)

	if brokerConfig.CFCCTarget != "" &&
		brokerConfig.CFUAATarget != "" &&
		brokerConfig.CFUser != "" &&
		brokerConfig.CFPassword != "" {

		registerCFServices = true
		var err error
		cfs, err = cfservices.New(brokerConfig.CFCCTarget, brokerConfig.CFUAATarget, brokerConfig.CFUser, brokerConfig.CFPassword)
		if err != nil {
			fmt.Println("Cannot connect to CF Services. - " + err.Error())
		}
	}

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

	r := martini.NewRouter()
	r.Get(`/v2/catalog`, GetCatalog)
	r.Put(`/v2/service_instances/:id`, Provision)
	r.Delete(`/v2/service_instances/:id`, Deprovision)
	r.Put(`/v2/service_instances/:instance_id/service_bindings/:id`, Bind)
	r.Delete(`/v2/service_instances/:instance_id/service_bindings/:id`, Unbind)
	r.Put(`/v2/services/:service_id/plans`, AddPlan)
	r.Delete(`/v2/services/:service_id/plans/:plan_id`, DeletePlan)

	m.Action(r.Handle)
}
Beispiel #18
0
func main() {
	log.UseStderr(true)
	log.SetV(9)
	flag.Parse()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	r := martini.NewRouter()

	tde := kv.NewTiedotEngine("./tiedotdb", []string{"short.url", "short.counter"}, kv.KeepIfExist)
	tde.AddIndex("short.url", kv.Path{"Short"})
	tde.AddIndex("short.counter", kv.Path{"Count"})

	if *useShort {
		log.Info("Starting LWS.short")
		s := short.NewShortener(tde)
		r.Any("/s", stripper("/s"), s.ServeHTTP)
		r.Any("/s/.*", stripper("/s"), s.ServeHTTP)
	}

	m.Action(r.Handle)
	http.ListenAndServe(*port, m)
}
Beispiel #19
0
func main() {
	tc := twilio.NewClient(twilioAccount, twilioKey, nil)
	mc := mailgun.NewMailgun(emailDomain, mailgunKey, mailgunPublicKey)

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

	m.Map(tc)
	m.MapTo(mc, (*mailgun.Mailgun)(nil))

	r.Post("/call", verifyTwilioReq, incomingCall)
	r.Post("/record-voicemail", verifyTwilioReq, recordVoicemail)
	r.Post("/voicemail", verifyTwilioReq, incomingVoicemail)
	r.Post("/sms", verifyTwilioReq, incomingSMS)
	r.Post("/email", incomingEmail)
	r.Post("/hangup", hangup)
	r.Get("/ping", func() {})

	go pinger()
	m.Run()
}
Beispiel #20
0
func init() {
	rand.Seed(time.Now().UTC().UnixNano())
	godotenv.Load("secrets.env")
	global.Tags = strings.Split(os.Getenv("TAGS"), ",")
	global.InstagramClientID = os.Getenv("INSTAGRAM_CLIENT_ID")
	global.TelegramKey = os.Getenv("TELEGRAM_KEY")

	m := martini.Classic()
	m.Use(appEngine)
	m.Use(render.Renderer())
	m.Use(martini.Logger())
	m.Get("/", func(r render.Render) {
		r.Redirect("https://telegram.me/QuestagBot", 302)
	})
	m.Post("/bothook", binding.Bind(telegram.Update{}), func(c context.Context, update telegram.Update, w http.ResponseWriter) {
		httpClient := urlfetch.Client(c)
		tele := telegram.NewTelegram(httpClient, global.TelegramKey)
		log.Infof(c, "%v", update)
		gamer, err := findOrCreateGamer(update, c)
		defer saveGamer(c, gamer)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			log.Errorf(c, "Can't find or create gamer: %v", err)
			return
		}
		log.Infof(c, "Gamer : %v", gamer.ChatID)

		if strings.Index(update.Message.Text, "/start") == 0 {
			log.Infof(c, "Start game with %v, %v", gamer.ChatID, update.Message.From.Username)
			gamer.handleStart()
			tele.SendPhoto(update.Message.Chat.ID, generateImage(gamer.GetCurrentQuestion(), httpClient), "", 0, gamer.GetKeyboard())
			return
		}
		if strings.Index(update.Message.Text, "/stop") == 0 {
			log.Infof(c, "Stop game with %v, %v", gamer.ChatID, update.Message.From.Username)
			gamer.handleStop()
			tele.SendMessage(update.Message.Chat.ID, "Game over", true, 0, nil)
			return
		}
		if strings.Index(update.Message.Text, "/status") == 0 {
			log.Infof(c, "Show game status for %v, %v", gamer.ChatID, update.Message.From.Username)
			tele.SendMessage(update.Message.Chat.ID, fmt.Sprintf("Your personal score:\nRight answers: %v\nWrong answers: %v\n%v accuracy", gamer.RightAnswers, gamer.WrongAnswers, gamer.GetAccuracy()*100), true, 0, nil)
			return
		}
		if strings.Index(update.Message.Text, "/top") == 0 {
			log.Infof(c, "Show top for %v, %v", gamer.ChatID, update.Message.From.Username)
			gamers, err := findBestGamer(c)
			count, _ := gamersCount(c)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				log.Errorf(c, "Can't find all gamers: %v", err)
				return
			}
			top := fmt.Sprintf("Top 20 gamers. Total gamers - %v\n", count)
			for i, g := range gamers {
				top += fmt.Sprintf("%v - %v, Right answers: %v, Wrong answers: %v\n", i+1, g.Username, g.RightAnswers, g.WrongAnswers)
			}
			tele.SendMessage(update.Message.Chat.ID, top, true, 0, nil)
			return
		}
		if strings.Index(update.Message.Text, "/help") == 0 {
			log.Infof(c, "Show help for %v, %v", gamer.ChatID, update.Message.From.Username)
			tele.SendMessage(update.Message.Chat.ID, HelpText, true, 0, nil)
			return
		}
		if gamer.isPlaying() {
			log.Infof(c, "Get answer from %v, %v on question %v", gamer.ChatID, update.Message.From.Username, gamer.GetCurrentQuestion())
			if gamer.handleAnswer(update.Message.Text) {
				log.Infof(c, "Right answer, gamer: %v, %v", gamer.ChatID, update.Message.From.Username)
				tele.SendMessage(update.Message.Chat.ID, "👍 Right!", true, 0, nil)
			} else {
				log.Infof(c, "Wrong answer, gamer: %v, %v", gamer.ChatID, update.Message.From.Username)
				tele.SendMessage(update.Message.Chat.ID, "😕 Wrong, "+gamer.GetCurrentQuestion().Answer, true, 0, nil)
			}
			tele.SendPhoto(update.Message.Chat.ID, generateImage(gamer.NextQuestion(), httpClient), "", 0, gamer.GetKeyboard())
			return
		}
		log.Infof(c, "Show help for %v, %v", gamer.ChatID, update.Message.From.Username)
		tele.SendMessage(update.Message.Chat.ID, HelpText, true, 0, nil)
	})
	http.Handle("/", m)
}
Beispiel #21
0
func threadHttp(config *wigo.HttpConfig) {
	apiAddress := config.Address
	apiPort := config.Port

	m := martini.New()

	if wigo.GetLocalWigo().GetConfig().Global.Debug {
		// Log requests
		m.Use(martini.Logger())
	}

	// Compress http responses with gzip
	if config.Gzip {
		log.Println("Http server : gzip compression enabled")
		m.Use(gzip.All())
	}

	// Add some basic security checks
	m.Use(secure.Secure(secure.Options{}))

	// Http basic auth
	if config.Login != "" && config.Password != "" {
		log.Println("Http server : basic auth enabled")
		m.Use(auth.Basic(config.Login, config.Password))
	}

	// Serve static files
	m.Use(martini.Static("public"))

	// Handle errors // TODO is this even working ?
	m.Use(martini.Recovery())

	// Define the routes.

	r := martini.NewRouter()

	r.Get("/api", func() (int, string) {
		json, err := wigo.GetLocalWigo().ToJsonString()
		if err != nil {
			return 500, fmt.Sprintf("%s", err)
		}
		return 200, json
	})

	r.Get("/api/status", func() string { return strconv.Itoa((wigo.GetLocalWigo().GlobalStatus)) })
	r.Get("/api/logs", wigo.HttpLogsHandler)
	r.Get("/api/logs/indexes", wigo.HttpLogsIndexesHandler)
	r.Get("/api/groups", wigo.HttpGroupsHandler)
	r.Get("/api/groups/:group", wigo.HttpGroupsHandler)
	r.Get("/api/groups/:group/logs", wigo.HttpLogsHandler)
	r.Get("/api/groups/:group/probes/:probe/logs", wigo.HttpLogsHandler)
	r.Get("/api/hosts", wigo.HttpRemotesHandler)
	r.Get("/api/hosts/:hostname", wigo.HttpRemotesHandler)
	r.Get("/api/hosts/:hostname/status", wigo.HttpRemotesStatusHandler)
	r.Get("/api/hosts/:hostname/logs", wigo.HttpLogsHandler)
	r.Get("/api/hosts/:hostname/probes", wigo.HttpRemotesProbesHandler)
	r.Get("/api/hosts/:hostname/probes/:probe", wigo.HttpRemotesProbesHandler)
	r.Get("/api/hosts/:hostname/probes/:probe/status", wigo.HttpRemotesProbesStatusHandler)
	r.Get("/api/hosts/:hostname/probes/:probe/logs", wigo.HttpLogsHandler)
	r.Get("/api/probes/:probe/logs", wigo.HttpLogsHandler)
	r.Get("/api/authority/hosts", wigo.HttpAuthorityListHandler)
	r.Post("/api/authority/hosts/:uuid/allow", wigo.HttpAuthorityAllowHandler)
	r.Post("/api/authority/hosts/:uuid/revoke", wigo.HttpAuthorityRevokeHandler)

	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.URL.Path, "/api") {
			w.Header().Set("Content-Type", "application/json")
		}
	})

	m.Action(r.Handle)

	// Create a listner and serv connections forever.
	if config.SslEnabled {
		address := apiAddress + ":" + strconv.Itoa(apiPort)
		log.Println("Http server : starting tls server @ " + address)
		tlsConfig := &tls.Config{MinVersion: tls.VersionTLS10}
		server := &http.Server{Addr: address, Handler: m, TLSConfig: tlsConfig}
		err := server.ListenAndServeTLS(config.SslCert, config.SslKey)
		if err != nil {
			log.Fatalf("Failed to start http server : %s", err)
		}
	} else {
		address := apiAddress + ":" + strconv.Itoa(apiPort)
		log.Println("Http server : starting plain http server @ " + address)
		if err := http.ListenAndServe(address, m); err != nil {
			log.Fatalf("Failed to start http server : %s", err)
		}
	}
}