Example #1
0
func main() {

	var wg sync.WaitGroup

	wg.Add(3)
	go func() {
		n := negroni.New()
		fmt.Println("Launching server on :3000")
		graceful.Run(":3000", 0, n)
		fmt.Println("Terminated server on :3000")
		wg.Done()
	}()
	go func() {
		n := negroni.New()
		fmt.Println("Launching server on :3001")
		graceful.Run(":3001", 0, n)
		fmt.Println("Terminated server on :3001")
		wg.Done()
	}()
	go func() {
		n := negroni.New()
		fmt.Println("Launching server on :3002")
		graceful.Run(":3002", 0, n)
		fmt.Println("Terminated server on :3002")
		wg.Done()
	}()
	fmt.Println("Press ctrl+c. All servers should terminate.")
	wg.Wait()

}
Example #2
0
func main() {
	var (
		addr  = flag.String("addr", ":8080", "endpoint address")
		mongo = flag.String("mongo", "localhost", "mongodb address")
	)
	flag.Parse()
	log.Println("Dialing mongo", *mongo)
	db, err := mgo.Dial(*mongo)
	if err != nil {
		log.Fatalln("failed to connect to mongo:", err)
	}
	defer db.Close()
	mux := http.NewServeMux()
	mux.HandleFunc("/polls/", withCORS(withVars(withData(db, withAPIKey(handlePolls)))))
	log.Println("Starting web server on", *addr)
	graceful.Run(*addr, 1*time.Second, mux)
	log.Println("Stopping...")
}
Example #3
0
// Run configured API service on the configured port. If you Registers
// middlewear for gziped responses and graceful shutdown with a 10
// second timeout.
func (a *APIApp) Run() error {
	var err error
	if !a.isResolved {
		err = a.Resolve()
	}

	n := negroni.New()
	for _, m := range a.middleware {
		n.Use(m)
	}

	n.UseHandler(a.router)

	listenOn := strings.Join([]string{a.address, strconv.Itoa(a.port)}, ":")
	grip.Noticeln("starting app on:", listenOn)

	graceful.Run(listenOn, 10*time.Second, n)
	return err
}
Example #4
0
func (a *API) Serve(addr string) {
	router := mux.NewRouter()

	v1 := router.PathPrefix("/1").Subrouter()

	// tasks
	tasksHandler := TasksHandler{a.store.Tasks()}

	task := v1.PathPrefix("/tasks/{id}").Subrouter()
	task.Methods("GET").HandlerFunc(tasksHandler.Get)
	task.Methods("PUT").HandlerFunc(tasksHandler.Set)
	task.Methods("DELETE").HandlerFunc(tasksHandler.Delete)
	task.Methods("POST", "PATCH").HandlerFunc(MethodNotAllowed)

	tasks := v1.PathPrefix("/tasks").Subrouter()
	tasks.Methods("GET").HandlerFunc(tasksHandler.List)
	tasks.Methods("POST").HandlerFunc(tasksHandler.Set)
	tasks.Methods("PUT", "DELETE", "PATCH").HandlerFunc(MethodNotAllowed)

	// events
	eventsHandler := EventsHandler{a.store.Events(), a.Events}

	event := v1.PathPrefix("/events/{id}").Subrouter()
	event.Methods("GET").HandlerFunc(eventsHandler.Get)
	event.Methods("PUT", "POST", "DELETE", "PATCH").HandlerFunc(MethodNotAllowed)

	events := v1.PathPrefix("/events").Subrouter()
	events.Methods("GET").HandlerFunc(eventsHandler.List)
	events.Methods("POST").HandlerFunc(eventsHandler.Create)
	events.Methods("PUT", "DELETE", "PATCH").HandlerFunc(MethodNotAllowed)

	// set up event handlers

	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negronilogrus.NewMiddleware())
	n.Use(gzip.Gzip(gzip.DefaultCompression))
	n.UseHandler(router)

	logrus.WithField("addr", addr).Info("listening")
	graceful.Run(addr, 10*time.Second, n)
}
Example #5
0
func main() {
	var vars Vars

	// Create logger.
	vars.log = log.NewLogger()
	vars.log.Info("initializing...")

	// Connect to the database.
	db, err := database.Connect(conf.C.DbType, conf.C.DbConn)
	if err != nil {
		vars.log.WithFields(logrus.Fields{
			"err":     err,
			"db_type": conf.C.DbType,
			"db_conn": conf.C.DbConn,
		}).Error("Could not connect to database")
		return
	}
	vars.db = db

	// Create datastore.
	vars.ds = database.NewDatastore(db)

	// Create router and add middleware.
	mux := router.New()

	mux.Use(webhelpers.Recoverer)
	mux.Use(middleware.Options)
	mux.Use(ContextMiddleware(&vars))
	mux.Use(middleware.SetHeaders)

	// We wrap the Request ID middleware and our logger 'outside' the mux, so
	// all requests (including ones that aren't matched by the router) get
	// logged.
	var handler http.Handler = mux
	handler = webhelpers.LogrusLogger(vars.log, handler)
	handler = webhelpers.RequestID(handler)

	// Start serving
	vars.log.Infof("starting server on: %s", conf.C.HostString())
	graceful.Run(conf.C.HostString(), 10*time.Second, handler)
	vars.log.Info("server finished")
}
Example #6
0
// RunHttpServer runs an HTTP server on a port defined by the PORT env var (default to 8080)
func RunHttpServer() {
	port := Getenv("PORT", "8080")
	publicDir := Getenv("PUBLIC_DIR", "public")

	c := NewContext()

	router := httprouter.New()
	router.GET("/", c.HomeHandler)
	router.GET("/stats", c.StatsHandler)

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir(publicDir)),
		c.Stats,
	)

	n.UseHandler(router)

	log.Printf("Starting openshift-dashboard on port %v\n", port)
	graceful.Run(":"+port, 10*time.Second, n)
}
Example #7
0
func main() {
	var httpPort = flag.Int("port", 8080, "port to listen on for HTTP")
	var dbHost = flag.String("dbhost", "localhost:27017", "host/port to connect to DB server")
	flag.Parse()

	session, err := mgo.Dial(*dbHost)
	if err != nil {
		fmt.Println(err)
		return
	}

	lk := logkeeper.New(session, logkeeper.Options{
		DB:  "buildlogs",
		URL: fmt.Sprintf("http://localhost:%v", *httpPort),
	})
	router := lk.NewRouter()
	n := negroni.Classic()
	n.Use(gzip.Gzip(gzip.DefaultCompression))
	n.UseHandler(router)

	graceful.Run(fmt.Sprintf(":%v", *httpPort), 10*time.Second, n)
}
Example #8
0
//Start starts selfie App, listeing to specified port
func (r *selfie) Start() {
	graceful.Run(r.conf.Server.Bind, 10*time.Second, web.New())
}
Example #9
0
func main() {
	log.Printf("initializing project_name=%q version=%q revision=%q",
		conf.ProjectName,
		conf.Version,
		conf.Revision)

	// Connect to the database.
	db, err := database.Connect(conf.C.DbType, conf.C.DbConn)
	if err != nil {
		log.Printf("could not connect to database err=%q db_type=%q db_conn=%q",
			err,
			conf.C.DbType,
			conf.C.DbConn)
		return
	}

	// Create datastore.
	ds := database.NewDatastore(db)

	// Create API router and add middleware.
	apiMux := router.API()
	apiMux.Use(middleware.Options)
	apiMux.Use(middleware.JSON)

	// Create web router.
	webMux := router.Web()

	// Create root mux and add common middleware.
	rootMux := goji.NewMux()
	rootMux.UseC(middleware.RequestID)
	rootMux.UseC(middleware.Logger)
	rootMux.UseC(middleware.Recoverer)
	rootMux.Use(middleware.SetHeaders)

	// Serve all static assets from the root.
	serveAssetAt := func(asset, path string) {
		info, _ := static.AssetInfo(asset)
		modTime := info.ModTime()
		data := static.MustAsset(asset)

		webMux.Handle(pat.Get(path), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			log.Printf("debug: serving asset: %s", asset)
			http.ServeContent(w, r, asset, modTime, bytes.NewReader(data))
		}))
	}
	for _, asset := range static.AssetNames() {
		log.Printf("debug: adding route for asset: %s", asset)
		serveAssetAt(asset, "/static/"+asset)
	}

	// Special case a bunch of assets that should be served from the root.
	for _, asset := range []string{
		"clientaccesspolicy.xml",
		"crossdomain.xml",
		"favicon.ico",
		"humans.txt",
		"robots.txt",
	} {
		// Note: only serve if we have this asset.
		if _, err := static.Asset(asset); err == nil {
			log.Printf("debug: adding special route for asset: %s", asset)
			serveAssetAt(asset, "/"+asset)
		}
	}

	// Serve the index page if we have one.
	for _, asset := range []string{"index.html", "index.htm"} {
		// Note: only serve if we have this asset, and only serve the first
		// option.
		if _, err := static.Asset(asset); err == nil {
			log.Printf("debug: adding index route for asset: %s", asset)
			serveAssetAt(asset, "/")
			break
		}
	}

	// Mount the API/Web muxes last (since order matters).
	rootMux.HandleC(pat.New("/api/*"), apiMux)
	rootMux.HandleC(pat.New("/*"), webMux)

	// Create a top-level wrapper that implements ServeHTTP, so we can inject
	// the root (Background) context and any other contexts that we wish to
	// inject.
	outer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.Background()
		ctx = datastore.NewContext(ctx, ds)
		rootMux.ServeHTTPC(ctx, w, r)
	})

	// Start serving
	log.Printf("starting server on: %s", conf.C.HostString())
	graceful.Run(conf.C.HostString(), 10*time.Second, outer)
	log.Printf("server finished")
}
Example #10
0
func CommandFunc(cmd *cobra.Command, args []string) {
	lp := strings.Replace(nowPacific().String()[:19], "-", "", -1)
	lp = strings.Replace(lp, ":", "", -1)
	lp = strings.Replace(lp, ".", "", -1)
	lp = strings.Replace(lp, " ", "", -1)

	usr, err := user.Current()
	if err != nil {
		fmt.Fprintln(os.Stdout, err)
	}

	f, err := openToAppend(filepath.Join(usr.HomeDir, "runetcd_"+lp+".log"))
	if err != nil {
		fmt.Fprintln(os.Stdout, err)
		return
	}
	defer f.Close()
	log.SetOutput(f)

	rootContext, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	mainRouter := http.NewServeMux()

	// mainRouter.Handle("/", http.FileServer(http.Dir("./demoweb_frontend")))
	mainRouter.Handle("/", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(staticHandler),
	})

	mainRouter.Handle("/ws", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(wsHandler)),
	})
	mainRouter.Handle("/stream", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(streamHandler)),
	})

	mainRouter.Handle("/start_cluster", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(startClusterHandler)),
	})
	mainRouter.Handle("/start_stress", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(startStressHandler)),
	})
	mainRouter.Handle("/stats", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(statsHandler)),
	})
	mainRouter.Handle("/metrics", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(metricsHandler)),
	})

	mainRouter.Handle("/list_ctl", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(listCtlHandler)),
	})
	mainRouter.Handle("/ctl", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(ctlHandler)),
	})

	mainRouter.Handle("/kill_1", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(killHandler)),
	})
	mainRouter.Handle("/kill_2", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(killHandler)),
	})
	mainRouter.Handle("/kill_3", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(killHandler)),
	})
	mainRouter.Handle("/restart_1", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(restartHandler)),
	})
	mainRouter.Handle("/restart_2", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(restartHandler)),
	})
	mainRouter.Handle("/restart_3", &ContextAdapter{
		ctx:     rootContext,
		handler: withUserCache(ContextHandlerFunc(restartHandler)),
	})

	fmt.Fprintln(os.Stdout, "Serving http://localhost"+webPort)
	// if err := http.ListenAndServe(webPort, mainRouter); err != nil {
	// 	fmt.Fprintln(os.Stdout, "[runetcd demo-web error]", err)
	// 	os.Exit(0)
	// }
	// graceful.Run(webPort, 10*time.Second, withLogrus(mainRouter))
	graceful.Run(webPort, 10*time.Second, mainRouter)
}
Example #11
0
func main() {
	router := mux.NewRouter()

	r := render.New()

	// New permissions middleware
	perm, _ := permissions.NewWithConf(configPath + "bolt.db")

	perm.AddUserPath("/api/holes/")
	perm.AddUserPath("/api/new_ca/")
	perm.AddUserPath("/api/new_cert/")
	perm.AddUserPath("/api/ca.pem")
	perm.AddUserPath("/api/ca.key")
	perm.AddUserPath("/api/cert.pem")
	perm.AddUserPath("/api/cert.key")

	// Get the userstate, used in the handlers below
	userstate := perm.UserState()

	creator := userstate.Creator()
	emails, _ := creator.NewKeyValue("emails")
	passwordTokens, _ := creator.NewKeyValue("password_tokens")
	usershole := NewUsersHole(userstate)

	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Hello HoleHub.")
	})

	router.HandleFunc("/api/signup/", func(w http.ResponseWriter, req *http.Request) {
		userForm := new(NewUserForm)
		errs := binding.Bind(req, userForm)
		if errs.Handle(w) {
			return
		}
		if userstate.HasUser(userForm.Name) {
			r.JSON(w, http.StatusOK, ErrorMessages[1])
			return
		}
		if name, _ := emails.Get(userForm.Email); name != "" {
			r.JSON(w, http.StatusOK, ErrorMessages[2])
			return
		}
		if !isEmail(userForm.Email) {
			r.JSON(w, http.StatusOK, ErrorMessages[3])
			return
		}
		userstate.AddUser(userForm.Name, userForm.Password, userForm.Email)
		emails.Set(userForm.Email, userForm.Name)
		GenerateUserCa(userForm.Name)
		GenerateUserCert(userForm.Name)
		users := userstate.Users()
		ca := userForm.Name + "-ca.pem"
		cakey := userForm.Name + "-ca.key"
		cert := userForm.Name + "-cert.pem"
		certkey := userForm.Name + "-cert.key"
		users.Set(userForm.Name, "ca", ca)
		users.Set(userForm.Name, "cakey", cakey)
		users.Set(userForm.Name, "cert", cert)
		users.Set(userForm.Name, "certkey", certkey)

		code, _ := userstate.GenerateUniqueConfirmationCode()
		userstate.AddUnconfirmed(userForm.Name, code)
		SendConfirmationCode(userForm.Name, userForm.Email, code)

		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/signin/", func(w http.ResponseWriter, req *http.Request) {
		authForm := new(AuthForm)
		errs := binding.Bind(req, authForm)
		if errs.Handle(w) {
			return
		}
		name := authForm.NameOrEmail
		if isEmail(authForm.NameOrEmail) {
			name, _ = emails.Get(authForm.NameOrEmail)
		}
		if !userstate.CorrectPassword(name, authForm.Password) {
			r.JSON(w, http.StatusOK, ErrorMessages[4])
			return
		}
		userstate.Login(w, name)
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/ping/", func(w http.ResponseWriter, req *http.Request) {
		var pong = []byte("false")
		if userstate.UserRights(req) {
			pong = []byte("true")
		}
		r.Data(w, http.StatusOK, pong)
	}).Methods("GET")

	router.HandleFunc("/api/holes/create/", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		req.ParseForm()
		scheme := req.Form.Get("scheme")
		holeName := req.Form.Get("name")

		hs := usershole.NewHoleApp(username, holeName, scheme)
		r.JSON(w, http.StatusOK, map[string]HoleApp{"hole": *hs})
	}).Methods("POST")

	router.HandleFunc("/api/holes/{holeID}/start/", func(w http.ResponseWriter, req *http.Request) {
		holeID := mux.Vars(req)["holeID"]
		username := userstate.Username(req)
		hs := usershole.GetOne(username, holeID)
		if hs == nil {
			r.JSON(w, http.StatusNotFound, ErrorMessages[10])
			return
		}
		hs.Start()
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/holes/{holeID}/kill/", func(w http.ResponseWriter, req *http.Request) {
		holeID := mux.Vars(req)["holeID"]
		username := userstate.Username(req)
		hs := usershole.GetOne(username, holeID)
		if hs == nil {
			hs = &HoleApp{ID: holeID}
		}
		hs.Kill()
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/holes/{holeID}/remove/", func(w http.ResponseWriter, req *http.Request) {
		holeID := mux.Vars(req)["holeID"]
		username := userstate.Username(req)
		if err := usershole.Remove(username, holeID); err != nil {
			r.JSON(w, http.StatusNotFound, ErrorMessages[10])
			return
		}
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/holes/{holeID}/", func(w http.ResponseWriter, req *http.Request) {
		holeID := mux.Vars(req)["holeID"]
		username := userstate.Username(req)
		hs := usershole.GetOne(username, holeID)
		if hs == nil {
			r.JSON(w, http.StatusNotFound, ErrorMessages[10])
			return
		}
		r.JSON(w, http.StatusOK, hs)
	}).Methods("GET")

	router.HandleFunc("/api/holes/", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		holes := usershole.GetAll(username)
		r.JSON(w, http.StatusOK, map[string][]*HoleApp{"holes": holes})
	}).Methods("GET")

	router.HandleFunc("/api/new_ca/", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		GenerateUserCa(username)
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/ca.pem", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		data, _ := ioutil.ReadFile(configPath + "certs/" + username + "-ca.pem")
		r.Data(w, http.StatusOK, data)
	}).Methods("GET")

	router.HandleFunc("/api/ca.key", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		data, _ := ioutil.ReadFile(configPath + "certs/" + username + "-ca.key")
		r.Data(w, http.StatusOK, data)
	}).Methods("GET")

	router.HandleFunc("/api/new_cert/", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		GenerateUserCert(username)
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/cert.pem", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		data, _ := ioutil.ReadFile(configPath + "certs/" + username + "-cert.pem")
		r.Data(w, http.StatusOK, data)
	}).Methods("GET")

	router.HandleFunc("/api/cert.key", func(w http.ResponseWriter, req *http.Request) {
		username := userstate.Username(req)
		data, _ := ioutil.ReadFile(configPath + "certs/" + username + "-cert.key")
		r.Data(w, http.StatusOK, data)
	}).Methods("GET")

	router.HandleFunc("/api/confirm/{confirmationCode}", func(w http.ResponseWriter, req *http.Request) {
		code := mux.Vars(req)["confirmationCode"]
		if err := userstate.ConfirmUserByConfirmationCode(code); err != nil {
			r.JSON(w, http.StatusOK, ErrorMessages[5])
			return
		}
		msg := ErrorMessages[0]
		r.JSON(w, http.StatusOK, msg)
	}).Methods("GET")

	router.HandleFunc("/api/resend/confirmationcode", func(w http.ResponseWriter, req *http.Request) {
		req.ParseForm()
		email := req.Form.Get("email")
		username, _ := emails.Get(email)

		if username == "" {
			r.JSON(w, http.StatusOK, ErrorMessages[7])
			return
		}

		if userstate.IsConfirmed(username) {
			r.JSON(w, http.StatusOK, ErrorMessages[6])
			return
		}

		code, _ := userstate.GenerateUniqueConfirmationCode()
		userstate.AddUnconfirmed(username, code)

		SendConfirmationCode(username, email, code)
		msg := ErrorMessages[0]
		r.JSON(w, http.StatusOK, msg)
	}).Methods("POST")

	router.HandleFunc("/api/reset_password/", func(w http.ResponseWriter, req *http.Request) {
		resetPasswordForm := new(ResetPasswordForm)
		errs := binding.Bind(req, resetPasswordForm)
		if errs.Handle(w) {
			return
		}
		var username string
		if userstate.UserRights(req) {
			username = userstate.Username(req)
			if !userstate.CorrectPassword(username, resetPasswordForm.OldPassword) {
				r.JSON(w, http.StatusOK, ErrorMessages[8])
				return
			}
		} else if resetPasswordForm.Token != "" {
			tokenStr, _ := passwordTokens.Get(resetPasswordForm.Token)
			passwordTokens.Del(resetPasswordForm.Token)
			var token map[string]string
			if err := json.Unmarshal([]byte(tokenStr), &token); err != nil {
				r.JSON(w, http.StatusOK, ErrorMessages[9])
				return
			}
			current := int(time.Now().Unix())
			expiredAt, _ := strconv.Atoi(token["expiredAt"])
			if expiredAt < current {
				r.JSON(w, http.StatusOK, ErrorMessages[9])
				return
			}
			username = token["username"]
			if !userstate.HasUser(username) {
				r.JSON(w, http.StatusOK, ErrorMessages[7])
				return
			}
		} else {
			http.Error(w, "Permission denied!", http.StatusForbidden)
		}
		users := userstate.Users()
		passwordHash := userstate.HashPassword(username, resetPasswordForm.NewPassword)
		users.Set(username, "password", passwordHash)
		r.JSON(w, http.StatusOK, ErrorMessages[0])
	}).Methods("POST")

	router.HandleFunc("/api/send/passwordToken", func(w http.ResponseWriter, req *http.Request) {
		req.ParseForm()
		username := req.Form.Get("username")
		if isEmail(username) {
			username, _ = emails.Get(username)
		}
		if !userstate.HasUser(username) {
			r.JSON(w, http.StatusOK, ErrorMessages[7])
			return
		}

		loop := 0
		var code string
		for {
			code, _ := userstate.GenerateUniqueConfirmationCode()
			tokenStr, _ := passwordTokens.Get(code)
			if tokenStr == "" {
				break
			}
			loop = loop + 1
			if loop > 1000 {
				http.Error(w, "Too many loops...", http.StatusInternalServerError)
				return
			}
		}

		email, _ := userstate.Email(username)
		expiredAt := time.Now().Add(12 * time.Hour).Unix()
		passwordTokens.Set(code, fmt.Sprintf("{\"username\": \"%s\", \"expiredAt\": \"%d\"}", username, expiredAt))

		SendPasswordToken(username, email, code)
		msg := ErrorMessages[0]
		r.JSON(w, http.StatusOK, msg)
	}).Methods("POST")

	// Custom handler for when permissions are denied
	perm.SetDenyFunction(func(w http.ResponseWriter, req *http.Request) {
		http.Error(w, "Permission denied!", http.StatusForbidden)
	})

	n := negroni.Classic()

	n.Use(perm)
	n.Use(cors.NewAllow(&cors.Options{AllowAllOrigins: true}))
	n.UseHandler(router)

	//n.Run(":3000")
	fmt.Printf("HoleHUB is run on http://%s:%d\n", host, port)
	graceful.Run(fmt.Sprintf("%s:%d", host, port), 10*time.Second, n)
}
Example #12
0
func (api *Api) Run() {
	fmt.Printf("Features is now ready to accept connections on port %s.", DEFAULT_PORT)
	graceful.Run(DEFAULT_PORT, DEFAULT_TIMEOUT, api.Handler())
}
Example #13
0
func (api *Api) Run() {
	Logger.Info(fmt.Sprintf("ApiHub is now ready to accept connections on port %s.", DEFAULT_PORT))
	graceful.Run(DEFAULT_PORT, DEFAULT_TIMEOUT, api.Handler())
}
Example #14
0
//Start starts Releasifier App, listeing to specified port
func (r *Releasifier) Start() {
	graceful.Run(r.conf.Server.Bind, 10*time.Second, web.New())
}
Example #15
0
func main() {
	var vars Vars

	// Create logger.
	vars.log = log.NewLogger()
	vars.log.WithFields(logrus.Fields{
		"project_name": conf.ProjectName,
		"version":      conf.Version,
		"revision":     conf.Revision,
	}).Info("initializing...")

	// Connect to the database.
	db, err := database.Connect(conf.C.DbType, conf.C.DbConn)
	if err != nil {
		vars.log.WithFields(logrus.Fields{
			"err":     err,
			"db_type": conf.C.DbType,
			"db_conn": conf.C.DbConn,
		}).Error("Could not connect to database")
		return
	}
	vars.db = db

	// Create datastore.
	vars.ds = database.NewDatastore(db)

	// Create API router and add middleware.
	apiMux := router.API()
	apiMux.Use(middleware.Options)
	apiMux.Use(middleware.JSON)

	// Create web router and add middleware.
	webMux := router.Web()
	webMux.Use(webhelpers.Recoverer)
	webMux.Use(ContextMiddleware(&vars))
	webMux.Use(middleware.SetHeaders)

	// "Mount" the API mux under the web mux, on the "/api" prefix.
	webMux.Handle("/api/*", apiMux)

	// Serve all static assets.
	serveAssetAt := func(asset, path string) {
		info, _ := static.AssetInfo(asset)
		modTime := info.ModTime()
		data := static.MustAsset(asset)

		webMux.Get(path, func(w http.ResponseWriter, r *http.Request) {
			vars.log.Debugf("serving asset: %s", asset)
			http.ServeContent(w, r, asset, modTime, bytes.NewReader(data))
		})
	}
	for _, asset := range static.AssetNames() {
		vars.log.Debugf("adding route for asset: %s", asset)
		serveAssetAt(asset, "/static/"+asset)
	}

	// Special case a bunch of assets that should be served from the root.
	for _, asset := range []string{
		"clientaccesspolicy.xml",
		"crossdomain.xml",
		"favicon.ico",
		"humans.txt",
		"robots.txt",
	} {
		// Note: only serve if we have this asset.
		if _, err := static.Asset(asset); err == nil {
			vars.log.Debugf("adding special route for asset: %s", asset)
			serveAssetAt(asset, "/"+asset)
		}
	}

	// Serve the index page if we have one.
	for _, asset := range []string{"index.html", "index.htm"} {
		// Note: only serve if we have this asset, and only serve the first
		// option.
		if _, err := static.Asset(asset); err == nil {
			vars.log.Debugf("adding index route for asset: %s", asset)
			serveAssetAt(asset, "/")
			break
		}
	}

	// We wrap the Request ID middleware and our logger 'outside' the mux, so
	// all requests (including ones that aren't matched by the router) get
	// logged.
	var handler http.Handler = webMux
	handler = webhelpers.LogrusLogger(vars.log, handler)
	handler = webhelpers.RequestID(handler)

	// Start serving
	vars.log.Infof("starting server on: %s", conf.C.HostString())
	graceful.Run(conf.C.HostString(), 10*time.Second, handler)
	vars.log.Info("server finished")
}