Пример #1
0
func (b *Broker) Run() {
	b.running = true
	b.RegisterMiddleware()
	b.RegisterURL()
	go b.HandleFailTask()
	graceful.ListenAndServe(b.web.Server(b.addr), 5*time.Second)
}
Пример #2
0
func main() {
	// inti config and component
	componentInit()

	// Echo instance
	e := echo.New()

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	// e.Use(handler.CrossDomain)

	// Routes
	e.Get("/hello", handler.Hello)
	e.Get("/api/v1/seckill", handler.Tickets)
	e.Get("/api/v1/reset", handler.Reset)

	// go cache.StartUpdateEventStatus()

	// go kafka.StartKafkaProducer()
	// Start server
	port := viper.GetString("port")
	log.Println("server port: ", port)
	graceful.ListenAndServe(e.Server(port), 1*time.Second)

}
Пример #3
0
func main() {
	port := "8080"

	e := echo.New()
	e.SetDebug(true)

	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.StripTrailingSlash()

	assetHandler := http.FileServer(assetFS())

	e.Get("/clicks", buttonsStateHandler)
	e.Post("/click/:button", buttonClicker)
	e.WebSocket("/ws", socketHandler)
	e.Get("/*", func(c *echo.Context) error {
		assetHandler.ServeHTTP(c.Response().Writer(), c.Request())
		return nil
	})

	// Start the "message hub"
	go hub.Run()

	// Detect clicks on buttons
	btns = newButtons()
	defer btns.Close()
	btns.Run()

	// Control the leds based on clicks
	newLeds(btns, hub)

	// Start server
	log.Println("Starting server on port " + port)
	graceful.ListenAndServe(e.Server(":"+port), 2*time.Second)
}
Пример #4
0
func main() {
	cfg := readConfig()
	jwtKey := []byte(cfg.JwtKey)

	mongoSession := createMongoSession()
	defer mongoSession.Close()

	db := mongoSession.DB(cfg.Database)
	userCollection := db.C(collections.UserCollectionName)

	e := echo.New()

	e.Get("/ping", func(c echo.Context) error {
		return c.String(http.StatusOK, "pong")
	})

	restService := rest.NewService(db)
	restGroup := e.Group("/collection")
	restGroup.Get("/:collection", restService.Get)
	restGroup.Post("/:collection", restService.Post)
	restGroup.Put("/:collection", restService.Put)
	restGroup.Delete("/:collection", restService.Delete)

	userService := user.NewService(userCollection, jwtKey)
	userGroup := e.Group("/user")
	userGroup.Post("/signup", userService.Signup)
	userGroup.Post("/confirm", userService.ConfirmSignup)
	userGroup.Post("/signin", userService.Signin)
	userGroup.Post("/forgot-password", userService.ForgotPassword)
	userGroup.Post("/reset-password", userService.ResetPassword)

	sessionService := session.NewService(userCollection, jwtKey)
	sessionMiddleware := middleware.CreateSessionMiddleware(userCollection, jwtKey)
	sessionGroup := e.Group("/session", sessionMiddleware)
	sessionGroup.Post("/signout", sessionService.Signout)
	sessionGroup.Post("/change-password", sessionService.ChangePassword)
	sessionGroup.Post("/change-email", sessionService.ChangeEmail)
	sessionGroup.Post("/set-profile", sessionService.SetProfile)

	adminService := admin.NewService(userCollection, jwtKey)
	adminSessionMiddleware := middleware.CreateAdminSessionMiddleware(userCollection, jwtKey)
	adminGroup := e.Group("/admin", adminSessionMiddleware)
	adminGroup.Get("/get-users", adminService.GetUsers)
	adminGroup.Post("/create-user", adminService.CreateUser)
	adminGroup.Post("/change-user-password", adminService.ChangeUserPassword)
	adminGroup.Post("/change-user-email", adminService.ChangeUserEmail)
	adminGroup.Post("/set-user-roles", adminService.SetUserRoles)
	adminGroup.Post("/set-user-profile", adminService.SetUserProfile)
	adminGroup.Delete("/remove-users", adminService.RemoveUsers)
	adminGroup.Post("/signout-users", adminService.SignoutUsers)
	adminGroup.Post("/suspend-users", adminService.SuspendUsers)
	adminGroup.Post("/unsuspend-users", adminService.UnsuspendUsers)
	adminGroup.Delete("/remove-unconfirmed-users", adminService.RemoveUnconfirmedUsers)
	adminGroup.Post("/remove-expired-reset-keys", adminService.RemoveExpiredResetKeys)

	fmt.Println("Listening at http://localhost:5025")
	std := standard.New(":5025")
	std.SetHandler(e)
	graceful.ListenAndServe(std.Server, 5*time.Second)
}
Пример #5
0
func main() {
	// ---------------------------
	// Setting Active Environment
	// ---------------------------

	if len(os.Args) > 1 {
		err := environment.Set(os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Fatal("Running requires an environment argument")
	}

	// ---------
	// Database
	// ---------

	db.Open()
	defer db.Close()

	// -----
	// Echo
	// -----

	e := request.BuildEcho()

	// ----
	// Run
	// ----

	port := environment.GetEnvVar(environment.PORT)
	log.Println("Server started on :" + port)
	graceful.ListenAndServe(e.Server(":"+port), 5*time.Second) // Graceful shutdown
}
Пример #6
0
func (s *ApiServer) Run() error {
	s.RegisterMiddleware()
	s.RegisterURL()
	std := standard.New(s.webAddr)
	std.SetHandler(s)
	graceful.ListenAndServe(std.Server, 5*time.Second)
	return nil
}
Пример #7
0
func main() {
	// Setup
	e := echo.New()
	e.Get("/", func(c *echo.Context) error {
		return c.String(http.StatusOK, "Sue sews rose on slow jor crows nose")
	})

	graceful.ListenAndServe(e.Server(":1323"), 5*time.Second)
}
Пример #8
0
func main() {
	e := echo.New()

	e.Use(mw.Logger())
	e.Use(mw.Recover())

	e.Post("/auth/register", controllers.AuthRegister)
	graceful.ListenAndServe(e.Server(":9000"), 10*time.Second)
}
Пример #9
0
func main() {
	// Setup
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Sue sews rose on slow joe crows nose")
	})
	std := standard.New(":1323")
	std.SetHandler(e)
	graceful.ListenAndServe(std.Server, 5*time.Second)
}
Пример #10
0
func main() {
	// Setup
	e := echo.New()
	e.Get("/", func(c *echo.Context) error {
		c.String(http.StatusOK, "Sue sews rose on slow jor crows nose")
		return nil
	})

	// Use github.com/tylerb/graceful
	graceful.ListenAndServe(e.Server(":1323"), 5*time.Second)
}
Пример #11
0
// main runs the jumphash program.
// There are two optional arguments, addr and seconds.
func main() {
	var addr = flag.String("address", "127.0.0.1:8080", "tcp address to listen on")
	var seconds = flag.Int("sleep", 5, "time in seconds to sleep each POST request")
	flag.Parse()
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(server.Shutdown())
	e.Use(server.Sleep(*seconds))
	e.Post("/", server.Hash)
	log.Printf("listening on %s", *addr)
	graceful.ListenAndServe(e.Server(*addr), 0)
}
Пример #12
0
func main() {
	// Echo instance
	e := echo.New()

	// Middleware
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	// Routes
	e.Get("/", hello)

	// Start server
	port := "8080"
	std := standard.New(":" + port)
	std.SetHandler(e)

	log.Printf("Starting app on port %+v\n", port)
	graceful.ListenAndServe(std.Server, 1*time.Second)
}
Пример #13
0
func (suite *ApiTestSuite) SetupTest() {
	// Loading .env file.  We're not failing here in the
	// event that the .env file can't be loaded. The
	// project might be running through a CI system
	// and the environment variables.  Will fail later
	// rather than early
	environment.SetWithRelativeDirectory("../", environment.TESTING)

	// Starting database
	db.Open()

	// Getting our Echo instance
	e := BuildEcho()

	// Running the server
	port := environment.GetEnvVar(environment.PORT)
	suite.wreckerClient = wrecker.New("http://localhost:" + port)
	log.Println("Server started on :" + port)
	go graceful.ListenAndServe(e.Server(":"+port), 5*time.Second) // Graceful shutdown
}
Пример #14
0
func main() {
	e := echo.New()

	// Enable colored log
	e.ColoredLog(true)

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())

	// https://github.com/thoas/stats
	s := stats.New()
	e.Use(s.Handler)
	// Route
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	// Serve index file
	e.Index("public/index.html")

	// Serve favicon
	e.Favicon("public/favicon.ico")

	// Serve static files
	e.Static("/scripts", "public/scripts")

	//-----------
	// Templates
	//-----------
	e.SetRenderer(controllers.CreateRenderer())
	e.Get("/page1", controllers.Page1Handler)
	e.Get("/page2", controllers.Page2Handler)

	// Start server
	log.Println("Server is starting for port 8080...")
	graceful.ListenAndServe(e.Server(":8080"), 2*time.Second)
	log.Println("Server stoped")
}
Пример #15
0
func main() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println("Running...")

	ctx = new(req.Context)

	l := new(store.Leveldb)
	l.SetBloomFilter(13)
	ctx.Store = l
	ctx.Store.Init("leveldb", "test")

	e := echo.New()
	e.SetDebug(true)
	e.Use(mw.Recover())
	e.Static("/assets/", "public/assets")
	e.Get("/webms/:name", func(c *echo.Context) error {
		resp := c.Response()
		name := c.Param("name")
		resp.Header().Add("Content-Type", "video/webm")
		http.ServeFile(resp, c.Request(), "webms/"+name)
		return nil
	})
	e.Static("/webms/", "webms")

	//e.ServeFile("/", "public/index.html")
	e.Get("/", func(c *echo.Context) error {
		http.ServeFile(c.Response(), c.Request(), "public/index.html")
		return nil
	})

	e.ServeFile("/upload", "public/upload.html")
	e.Post("/upload", func(c *echo.Context) error {
		req := c.Request()

		name := req.FormValue("name")
		ttags := req.FormValue("tags")
		tags := strings.Split(ttags, " ")
		path := x.UniqueString(10)

		// Read files
		file := req.MultipartForm.File["file"]
		src, err := file[0].Open()
		if err != nil {
			return err
		}
		defer src.Close()

		// Destination file
		dst, err := os.Create("webms/" + path + ".webm")
		if err != nil {
			return err
		}
		defer dst.Close()

		if _, err = io.Copy(dst, src); err != nil {
			return err
		}

		if err = api.Get("WebmCont", rootid).SetSource(rootid).AddChild("Webm").Set("path", path).
			Set("tags", tags).Set("name", name).Execute(ctx); err != nil {
			return err
		}

		return c.String(http.StatusOK, "eyo uploaded file")
	})

	e.Get("/webm", func(c *echo.Context) error {
		result, err := api.NewQuery("WebmCont", rootid).Collect("Webm").Run(ctx)
		if err != nil {
			return err
		}
		by, err := result.ToJson()
		if err != nil {
			return err
		}
		return c.String(200, string(by))
	})

	e.Get("/webm/filter/:filter", func(c *echo.Context) error {
		tags := strings.Split(c.Param("filter"), "+")
		result, err := api.NewQuery("WebmCont", rootid).Collect("Webm").Run(ctx)
		if err != nil {
			return err
		}
		by, err := filter(result, tags...)
		if err != nil {
			return err
		}
		return c.String(200, string(by))
	})

	e.Get("/webm/:id", func(c *echo.Context) error {
		result, err := api.NewQuery("Webm", c.Param("id")).Run(ctx)
		if err != nil {
			return err
		}
		by, err := result.ToJson()
		if err != nil {
			return err
		}
		return c.String(200, string(by))
	})

	e.Get("/webm/:id/tag/:tag", func(c *echo.Context) error {
		result, err := api.NewQuery("Webm", c.Param("id")).Run(ctx)
		if err != nil {
			return err
		}
		var tags []interface{}
		tagb, ok := result.Columns["tags"].Value.([]interface{})
		if ok {
			tags = tagb
		}
		cont := contains(tags, c.Param("tag"))
		var atags []string
		var resp string
		if cont {
			resp = "removed"
			atags = convertButLeave(tags, c.Param("tag"))
		} else {
			resp = "added"
			atags = convert(tags)
			atags = append(atags, c.Param("tag"))
		}
		err = api.Get("Webm", c.Param("id")).SetSource(rootid).Set("tags", atags).Execute(ctx)
		if err != nil {
			return err
		}

		return c.String(200, resp)
	})

	graceful.ListenAndServe(e.Server(":8080"), 5*time.Second)
}
Пример #16
0
func (s *Server) Run() {
	s.registerGlobalMiddlewares()
	controller.RegisterURLs(s.web)
	fmt.Printf("runing on %s\n", s.httpAddr)
	graceful.ListenAndServe(s.web.Server(s.httpAddr), 5*time.Second)
}
Пример #17
0
func main() {
	var port string
	if port = os.Getenv("VCAP_APP_PORT"); len(port) == 0 {
		port = DEFAULT_PORT
	}

	var host string
	if host = os.Getenv("VCAP_APP_HOST"); len(host) == 0 {
		host = DEFAULT_HOST
	}

	// prepare folder for DB with sample data
	dir := "./.fakedata-db"
	os.RemoveAll(dir)
	defer os.RemoveAll(dir)

	var tiedot *db.DB
	var err error

	// init sample data
	if tiedot, err = db.OpenDB(dir); err != nil {
		log.Panic(err)
	}
	defer tiedot.Close()

	// init sample data
	if err = fakedata.AddData(tiedot); err != nil {
		log.Panic(err)
	}

	// init persistence stores
	rest.SetProductStore(data.GetProductStore(tiedot))

	// Echo instance
	e := echo.New()

	// Static test web pages
	e.Static("/", "website")
	e.Index("website/index.html")

	// Customization
	e.SetDebug(true)

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())

	// Routes
	routes(e)

	s := e.Server(host + ":" + port)

	// HTTP2 is currently enabled by default in echo.New(). To override TLS handshake errors
	// you will need to override the TLSConfig for the server so it does not attempt to validate
	// the connection using TLS as required by HTTP2
	s.TLSConfig = nil

	// Start server
	log.Printf("Starting app on %+v:%+v\n", host, port)
	graceful.ListenAndServe(s, 5*time.Second)
}
Пример #18
0
func main() {
	routes := NewRoutes()
	graceful.ListenAndServe(routes.Server(":60000"), 5*time.Second)
}
Пример #19
0
func gracefulRun(std *standard.Server) {
	log.Fatal(graceful.ListenAndServe(std.Server, 5*time.Second))
}
Пример #20
0
func main() {
	e := echo.New()

	e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c *echo.Context) error {
			start := time.Now()

			entry := log.WithFields(log.Fields{
				"uuid":   uuid4(),
				"path":   c.Request().RequestURI,
				"method": c.Request().Method,
				"ip":     c.Request().RemoteAddr,
			})

			if reqID := c.Request().Header.Get("X-Request-Id"); reqID != "" {
				entry = entry.WithField("request_id", reqID)
			}

			entry.Info("started handling request")

			if err := next(c); err != nil {
				c.Error(err)
			}

			latency := time.Since(start)

			entry.WithFields(log.Fields{
				"status":      c.Response().Status(),
				"text_status": http.StatusText(c.Response().Status()),
				"took":        latency,
				fmt.Sprintf("measure#%s.latency", "web"): latency.Nanoseconds(),
			}).Info("completed handling request")

			return nil
		}
	})
	e.Use(mw.Recover())
	startTime := time.Now()

	if time.Since(startTime).Minutes() >= 3 {
		// finish game
	}

	e.Static("/", "public")
	e.WebSocket("/ws", func(c *echo.Context) (err error) {
		ws := c.Socket()
		if err = websocket.Message.Send(ws, "Please Login"); err != nil {
			return err
		}
		msg := ""
		for {
			// if err = websocket.Message.Send(ws, "Hello, Client!"); err != nil {
			// return err
			// }
			if err = websocket.Message.Receive(ws, &msg); err != nil {
				if err == io.EOF {
					return nil
				}
			}
			if strings.Contains(msg, "login") {
				// split get tokenString
				// checkToken(tokenString)
				// if valid {
				// login
				// } else {
				// return
				// }
			} else if strings.Contains(msg, "join_game") {
			} else if strings.Contains(msg, "leave_game") {
			}
			log.Info(msg)
		}
		ws.Close()
		return nil
	})
	log.Info("Starting websocket server at localhost:4000")
	graceful.ListenAndServe(e.Server(":4000"), 3*time.Minute)
}
Пример #21
0
func main() {
	// Echo instance
	e := echo.New()

	// Middleware echo
	e.Use(middleware.Logger())
	logg := e.Logger()

	e.Use(middleware.Recover())
	e.Use(middleware.Gzip())
	e.Use(middleware.Secure())
	e.Use(middleware.CORS())
	e.Use(middleware.BodyLimit("200M"))

	// gopkg.in/mgo.v2
	db := midd.NewMgo(viper.GetString("db.url"), viper.GetString("db.name"))
	defer db.Session.Close()
	e.Use(midd.Mgo(db))

	// github.com/thoas/stats
	middStat := stats.New()
	e.Use(standard.WrapMiddleware(middStat.Handler))
	// Route for stats
	e.Get("/stats", echo.HandlerFunc(func(c echo.Context) error {
		return c.JSON(http.StatusOK, middStat.Data())
	}))

	// API v1 Restricted group Token in header
	api := e.Group("/apiv1")
	api.Use(middleware.JWTWithConfig(middleware.JWTConfig{
		SigningKey:  []byte(midd.SigningKey),
		TokenLookup: "header:Authorization"}))
	api.Post("/user", handler.PostUser)
	api.Get("/user/:id", handler.GetUser)

	// API v1 Token as first param
	apit := e.Group("/apiv1token")
	apit.Use(middleware.JWTWithConfig(middleware.JWTConfig{
		SigningKey:  []byte(midd.SigningKey),
		TokenLookup: "query:token"}))
	apit.Post("/user", handler.PostUser)
	apit.Get("/user/:id", handler.GetUser)

	// Serve index file
	e.File("/", "public/index.html")
	// Serve favicon
	e.File("/favicon.ico", "public/favicon.ico")
	// Serve static files
	e.Static("/scripts", "public/scripts")

	midd.GenerateToken()

	// Get server info
	var svrHostname string

	if runtime.GOOS == "windows" {
		svrHostname = fmt.Sprintf("%s.%s", os.Getenv("COMPUTERNAME"), os.Getenv("USERDNSDOMAIN"))
	} else {
		svrHostname, _ = os.Hostname()
	}
	webInterfacePort := viper.GetString("web.interface")

	logg.Printf("%s for %s %s on %d cores\n%s%s\n",
		runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.NumCPU(), svrHostname, webInterfacePort)

	mgoInfo, _ := db.Session.BuildInfo()
	logg.Printf("MongoDB %s %d bits\n", mgoInfo.Version, mgoInfo.Bits)

	// github.com/tylerb/graceful
	std := standard.New(webInterfacePort)
	std.SetHandler(e)
	graceful.ListenAndServe(std.Server, 5*time.Second)
}