Example #1
0
func main() {

	loggerService.FileHandle = "server.go"
	loggerService.ErrMsg = string("init server.go")
	loggerService.Count = len("init server.go")
	loggerService.Level = "DEBUG"
	gLoggerService.LogInit(loggerService)
	go putEnginePoll()
	// Echo instance
	e := echo.New()

	// Debug mode
	e.Debug()

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

	// Routes
	e.Get("/expressListUsers", expressListUsers)
	e.Post("/expressEmailMessage", expressEmailMessage)
	e.Post("/expressQueryUsers", expressQueryUsers)
	e.Post("/expressTake", expressTake)
	e.Get("/expressTakeUser", expressTakeUser)

	loggerService.FileHandle = "server.go"
	loggerService.ErrMsg = string("1323 succ server.go")
	loggerService.Count = len("1323 succ server.go")
	loggerService.Level = "DEBUG"
	gLoggerService.LogInit(loggerService)
	// Start server
	e.Run(":1323")
}
Example #2
0
func main() {
	// Echo instance
	e := echo.New()

	// Debug mode
	e.Debug()

	//------------
	// Middleware
	//------------

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

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

	// Basic auth
	e.Use(mw.BasicAuth(func(usr, pwd string) bool {
		if usr == "joe" && pwd == "secret" {
			return true
		}
		return false
	}))

	// Gzip
	e.Use(mw.Gzip())

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

	// Start server
	e.Run(":1323")
}
Example #3
0
func Init() *echo.Echo {

	e := echo.New()

	e.Debug()

	// Set Bundle MiddleWare
	e.Use(echoMw.Logger())
	e.Use(echoMw.Gzip())
	e.Use(echoMw.CORSWithConfig(echoMw.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAcceptEncoding},
	}))
	e.SetHTTPErrorHandler(handler.JSONHTTPErrorHandler)

	// Set Custom MiddleWare
	e.Use(myMw.TransactionHandler(db.Init()))

	// Routes
	v1 := e.Group("/api/v1")
	{
		v1.POST("/members", api.PostMember())
		v1.GET("/members", api.GetMembers())
		v1.GET("/members/:id", api.GetMember())
	}
	return e
}
Example #4
0
// setup prepares the internal HTTP handle, middleware, and resources.
func (s *Server) setup() {
	e := echo.New()
	s.core = e

	// Enable HTTP 2
	e.HTTP2(true)

	// Toggle debug
	e.SetDebug(s.Debug)

	// Setup middleware.
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())

	// Setup CORS.
	e.Use(cors.New(cors.Options{
		AllowedOrigins: s.AllowedHosts,
	}).Handler)

	// Add middleware for setting the server context.
	e.Use(s.serverContext)

	e.Get("/", httpRoot)
	e.Get("/domains", httpDomains)

	e.Get("/log/:domain", httpLog)
	e.Get("/log/:domain/entities", httpDomainEntities)
	e.Get("/log/:domain/attributes", httpDomainAttributes)
	e.Get("/log/:domain/values", httpDomainValues)

	e.Get("/timeline/:domain", httpTimeline)
}
Example #5
0
func server(config config, db *sql.DB) *echo.Echo {
	dbx := sqlx.NewDb(db, "postgres")
	exec := echo.New()
	if !config.Production {
		exec.Debug()
	}
	exec.Use(mw.Logger())
	exec.Use(mw.Recover())
	exec.Use(mw.Gzip())

	exec.Get("/status", func(c *echo.Context) error {
		return c.NoContent(http.StatusOK)
	})

	leadHandler := lead.NewHandler(datastores.NewLead(dbx))

	exec.Post("/lead", leadHandler.Create)
	exec.Get("/lead/:hashCode", leadHandler.CountByInvites)

	assetHandler := http.FileServer(rice.MustFindBox("static").HTTPBox())
	exec.Get("/", func(c *echo.Context) error {
		assetHandler.ServeHTTP(c.Response().Writer(), c.Request())
		return nil
	})
	exec.Get("/static/*", func(c *echo.Context) error {
		http.StripPrefix("/static/", assetHandler).
			ServeHTTP(c.Response().Writer(), c.Request())
		return nil
	})

	return exec
}
Example #6
0
func main() {
	//runtime.GOMAXPROCS(runtime.NumCPU())
	e := echo.New()

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

	e.Get("/", welcome)
	e.Get("/ping", ping)

	//// Start server
	//e.Run(":1323")

	// Get the http.Server
	s := e.Server(":8000")

	// 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

	// Serve it like a boss
	log.Fatal(gracehttp.Serve(s))
}
Example #7
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	fetchFeed()

	e := echo.New()
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.StripTrailingSlash())
	e.Use(mw.Gzip())
	e.Use(cors.Default().Handler)

	bundle, _ := ioutil.ReadFile("./build/bundle.js")

	// stats
	s := stats.New()
	e.Use(s.Handler)
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})
	// static files
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")
	e.Favicon("public/favicon.ico")

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), rss))
	e.Get("/about", selfjs.New(runtime.NumCPU(), string(bundle), loremJSON()))

	e.Get("/api/data", apiFrontPage)
	e.Get("/api/anotherpage", apiAnotherPage)
	go tick()
	fmt.Println("serving at port 3000")
	e.Run(":3000")
}
Example #8
0
func main() {
	echo_serve := echo.New()

	mws := []echo.Middleware{mw.Logger(), mw.Recover(), mw.Gzip()}
	//注册日志、故障恢复、响应Gzip压缩中间件
	echo_serve.Use(mws...)

	//	echo_serve.Static("/","templates")
	//	echo_serve.Static("/js","sources/scripts")
	//	echo_serve.Static("/css","sources/css")
	//
	//	echo_serve.Index("templates/index.html")

	tmpl, err := template.ParseGlob("templates/*.html")
	if err != nil {
		fmt.Print(err.Error())
	}

	t := &Template{
		templates: template.Must(tmpl, err),
	}
	echo_serve.SetRenderer(t)
	echo_serve.Get("/hello", Hello)

	echo_serve.Run(":9060")
}
Example #9
0
func main() {
	fromEmail = os.Getenv("FROMEMAIL")
	emailSendingPasswd = os.Getenv("EMAILSENDINGPASSWD")
	if fromEmail == "" || emailSendingPasswd == "" {
		log.Fatal("FROMEMAIL or EMAILSENDINGPASSWD was not set")
	}
	runtime.GOMAXPROCS(runtime.NumCPU())
	app := NewApplication()
	app.Init()
	e := echo.New()

	e.Use(middleware.HttpLogger())
	e.HTTP2()
	e.SetHTTPErrorHandler(app.errorHandler)
	e.Use(mw.Recover())
	e.Use(mw.Gzip())
	e.StripTrailingSlash()
	e.Use(cors.Default().Handler)
	/* TODO: logs too much
	newrelickey, found := os.LookupEnv("NEWRELICKEY")
	if found == true {
		gorelic.InitNewRelicAgent(newrelickey, "go-register-login", true)
		e.Use(gorelic.Handler())
	}
	*/
	s := stats.New()
	e.Use(s.Handler)

	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	e.Favicon("public/favicon.ico")
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")

	bundle, _ := ioutil.ReadFile("./build/bundle.js")
	user, _ := json.Marshal(domain.User{})

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/register", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/login", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))

	admin := e.Group("/members")
	admin.Use(middleware.CheckAdmin(app.Redis, string(bundle)))
	admin.Get("", selfjs.New(runtime.NumCPU(), string(bundle), app.listUsers()))

	e.Get("/api/users", app.listUsersAPI)
	e.Get("/api/user/:id", app.userAPI)
	e.Get("/verify/:id/:hash", app.verifyEmail)
	e.Post("/register", app.createUser)
	e.Get("/logout", app.logout)
	e.Post("/login", app.login)
	fmt.Println("Starting server at port 3300")
	e.Run(":3300")
}
Example #10
0
func main() {
	e := echo.New()
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())

	e.Static("/", "public")

	e.Run(":5091")
}
Example #11
0
// StartHTTP listens on the configured ports for the REST application
func (s *Service) StartHTTP() error {
	address := fmt.Sprintf("%s:%d", s.config.Interface, s.config.Port)

	URL = address
	// Use middlewares
	s.Router.Use(mw.Gzip())
	s.Router.Use(mw.Logger())
	s.Router.Run(standard.New(address))

	return nil
}
Example #12
0
func createMux() *echo.Echo {
	e := echo.New()

	e.Use(middleware.Recover())
	e.Use(middleware.Logger())
	e.Use(middleware.Gzip())

	e.Static("/", "public")

	return e
}
Example #13
0
func createMux() *echo.Echo {
	e := echo.New()

	e.Use(middleware.Recover())
	e.Use(middleware.Logger())
	e.Use(middleware.Gzip())

	e.Index("public/index.html")
	e.Static("/public", "public")

	return e
}
func initApp() *echo.Echo {
	// create router and stats handler
	e := echo.New()

	// why not, it's fast and "the future" ...
	e.HTTP2(true)

	// add middleware
	e.Use(
		middleware.Recover(),
		middleware.Logger(),
		middleware.Gzip())
	return e
}
Example #15
0
func main() {
	e := echo.New()
	e.StripTrailingSlash()
	e.Use(middleware.Logger())
	e.Use(middleware.Gzip())
	e.Use(middleware.Recover())
	e.Use(cors.Default().Handler)

	e.Get("/user", getHandlerFunc(models.GetUsers))
	e.Get("/store", getHandlerFunc(models.GetStores))
	e.Get("/deal", getHandlerFunc(models.GetDeals))

	e.Run(":3000")
}
Example #16
0
//	启动服务
func Start() {

	e := echo.New()

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

	//	注册路由
	registerRoute(e)

	log.Printf("启动Http服务,端口:%d", config.Get().Port)
	// Start server
	e.Run(fmt.Sprintf(":%d", config.Get().Port))
}
Example #17
0
func New() *echo.Echo {
	server = echo.New()

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

	// Serve index
	server.Index("static/index.html")

	// Static Files
	server.Static("/js", "static/js")
	server.Static("/css", "static/css")
	server.Static("/img", "static/img")

	return server
}
Example #18
0
func Run(host string, port int) {
	s := echo.New()
	s.SetLogLevel(glog.FATAL)
	s.Use(echologrus.New(), middleware.Recover(), middleware.Gzip())
	s.SetRenderer(NewRenderer())
	s.Get("/assets/*", http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo}))
	s.Get("/data/*", http.FileServer(
		&assetfs.AssetFS{Asset: govatar.Asset, AssetDir: govatar.AssetDir, AssetInfo: govatar.AssetInfo}))

	s.Get("/", index)
	s.Get("/settings", settings)
	s.Post("/download", download)

	addr := fmt.Sprintf("%s:%d", host, port)
	log.Infof("Starting server on %s", addr)
	s.Run(addr)
}
Example #19
0
func main() {
	//Echo instance
	e := echo.New()

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

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

	//open debug
	e.SetDebug(true)

	//start server
	e.Run(":1234")
}
Example #20
0
func main() {
	mongoURL := flag.String("mongodb", "mongodb://localhost/watch", "MongoDB connection URL")
	addr := flag.String("http", ":8080", "Server address & port")
	docker := flag.Bool("docker", false, "for docker")
	flag.Parse()

	// Если запускается внутри контейнера
	if *docker {
		tmp := os.Getenv("MONGODB")
		mongoURL = &tmp
	}

	mdb, err := mongo.Connect(*mongoURL)
	if err != nil {
		log.Println("Error connecting to MongoDB:", err)
		return
	}
	defer mdb.Close()

	// инициализируем хранилище с информацией о треках
	tracksDB, err = tracks.InitDB(mdb)
	if err != nil {
		log.Println("Error initializing TrackDB:", err)
		return
	}
	// инициализируем хранилище с информацией о местах
	placesDB, err = places.InitDB(mdb)
	if err != nil {
		log.Println("Error initializing PlaceDB:", err)
		return
	}

	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(middleware.Gzip())
	e.SetRenderer(&Template{templates: template.Must(
		template.ParseFiles("index.html", "current.html", "history.html"))})
	e.Get("/", index)
	e.Get("/:deviceid", current)
	e.Get("/:deviceid/history", history)
	e.ServeFile("/edit", "placeeditor.html")
	e.Run(*addr)
}
Example #21
0
File: main.go Project: Code-Hex/req
func main() {
	e := echo.New()

	os.Setenv("REQ-MODE", "development")
	if os.Getenv("REQ-MODE") == "development" {
		e.Use(middleware.Logger())
		e.SetDebug(false)
	}

	e.Use(middleware.Recover())
	e.Use(middleware.Gzip())

	e.GET("/", index)
	e.GET("/healthcheck", healthcheck)

	e.Static("/assets", "../assets")

	e.Run(standard.New(":4000"))
}
Example #22
0
// EchoServer is echo version of http server
func EchoServer() {
	e := echo.New()

	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())
	//
	e.Static("/", "web/static")

	t := &Template{
		// Cached templates
		templates: template.Must(template.New("index.html").Funcs(funcMap).ParseFiles("web/templates/index.html")),
	}
	// t.templates.Funcs(funcMap)
	e.SetRenderer(t)

	e.Get("/", index)

	e.Run(":3000")
}
Example #23
0
func main() {
	cfg := config.Load()
	db := database.Connect(cfg.DatabaseURL)
	defer db.Close()
	ds := database.NewDatastore(db)

	e := echo.New()

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

	e.Get("/ping", ping.Index())
	e.Get("/ceps", cep.Index(ds))
	e.Get("/ceps/:cep", cep.Search(ds))
	e.Post("/ceps", cep.Insert(ds))
	e.Put("/ceps/:cep", cep.Update(ds))

	log.Println("Running on port", cfg.Port)
	e.Run(":" + cfg.Port)
}
Example #24
0
func main() {
	var err error
	globalData, err = LoadData()
	if err != nil {
		fmt.Println("data.json not found")
		panic(err)
	}
	go globalData.UpdateDB(false)

	e := echo.New()

	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())
	})

	e.Static("/css", "public/css")
	e.Static("/fonts", "public/fonts")
	e.Static("/img", "public/img")
	e.Static("/js", "public/js")

	t := &Template{
		templates: template.Must(template.ParseFiles("public/index.html")),
	}
	e.SetRenderer(t)
	e.Get("/update", update)
	e.Get("/raw", raw)
	e.Get("/", welcome)
	fmt.Println("starting on :80")
	go updateDB()
	// Start server
	e.Run(":80")
}
Example #25
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")
}
Example #26
0
// Serve sets up and starts the server
func (s *APIServer) Serve() error {
	e := echo.New()
	e.Debug = true
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(middleware.CORS())
	e.Use(middleware.BodyLimit("1024K"))
	e.Use(middleware.Gzip())

	// Serve the ember app
	e.File("/", "assets/index.html")
	e.Static("/assets", "assets/assets")

	//	e.OPTIONS("/api/login/", s.updateUser)
	e.POST("/api/login/", s.login)

	// Restricted group
	r := e.Group("/api/v1")
	r.Use(middleware.JWT([]byte("secret")))
	r.Use(s.getDBUser)
	r.GET("/feeds", s.getFeeds)
	r.POST("/feeds", s.addFeed)
	r.GET("/feeds/:id", s.getFeed)
	r.PATCH("/feeds/:id", s.updateFeed)
	r.PUT("/feeds/:id/subscribe", s.subFeed)
	r.PUT("/feeds/:id/unsubscribe", s.unsubFeed)

	customServer := &http.Server{
		Addr:           fmt.Sprintf(":%d", s.Port),
		ReadTimeout:    20 * time.Second,
		WriteTimeout:   20 * time.Second,
		MaxHeaderBytes: 2048,
	}

	err := e.StartServer(customServer)
	if err != nil {
		return fmt.Errorf("Error starting server: %s", err)
	}
	return nil
}
Example #27
0
func main() {

	t := &Template{
		templates: template.Must(template.ParseGlob("../website/public/hello.html")),
	}

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

	// Debug mode
	e.Debug()

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

	e.SetRenderer(t)

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

	e.Use(func(c *echo.Context) error {
		println(c.Path()) // Prints `/users/:name`
		return nil
	})

	e.Get("/expressListUsers", expressListUsers)
	e.Get("/expressQueryUsers", expressQueryUsers)
	e.Get("/expressEmailMessage", expressEmailMessage)

	e.Get("/users/:name", func(c *echo.Context) error {
		// By name
		name := c.Param("name")
		return c.String(http.StatusOK, name)
	})

	// Start server
	e.Run(":1323")
}
Example #28
0
func main() {
	kingpin.Parse()
	port := ":" + strconv.Itoa(*portNum)

	e := echo.New()
	e.Debug()

	if *logs {
		e.Use(middleware.Logger())
	}

	e.Use(middleware.Recover())
	e.Use(middleware.Gzip())

	e.Static("/static", path.Join(*assets))

	e.Post("/log", handler())

	e.File("/", path.Join(*assets, "index.html"))

	fmt.Println("Listening on port " + strconv.Itoa(*portNum))
	e.Run(standard.New(port))
}
Example #29
0
// Run the MicroServer
func main() {

	LoadConfig()

	// Connect to the SQLServer
	var err error

	db, err = sql.Open("postgres", itrak.DataSourceName)
	defer db.Close()
	if err != nil {
		log.Fatalln("Exiting ..")
	}

	// Setup the web server
	e := echo.New()

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

	c := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{"GET", "POST", "DELETE", "PUT", "PATCH"},
		AllowCredentials: true,
		Debug:            itrak.Debug,
	})
	e.Use(c.Handler)

	loadHandlers(e)

	// Start the web server
	if itrak.Debug {
		log.Printf("Starting Web Server of port %d ...", itrak.WebPort)
	}
	e.Run(fmt.Sprintf(":%d", itrak.WebPort))
}
Example #30
0
func Init() *echo.Echo {
	t := &Template{
		templates: template.Must(template.ParseGlob("templates/*.html")),
	}
	e := echo.New()
	e.Static("/assets", "public")

	e.Debug()

	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())
	e.Use(mw.CORSWithConfig(mw.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAcceptEncoding},
	}))
	e.SetHTTPErrorHandler(handler.JSONHTTPErrorHandler)

	e.SetRenderer(t)

	// set custome middleware
	e.Use(sckMw.TransactionHandler(db.Init()))

	// view
	e.GET("/", handler.Home)
	e.GET("/snippet", handler.Snippet)
	e.GET("/create", handler.SnippetCreate)

	// api
	v1 := e.Group("/api/v1")
	{
		v1.POST("/snippet/create", api.Create())
		v1.POST("/preview", api.Preview())
	}
	return e
}