func TestGzip(t *testing.T) { req, _ := http.NewRequest(echo.GET, "/", nil) rec := httptest.NewRecorder() c := echo.NewContext(req, echo.NewResponse(rec), echo.New()) h := func(c *echo.Context) error { c.Response().Write([]byte("test")) // Content-Type sniffing return nil } // Skip if no Accept-Encoding header Gzip()(h)(c) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "test", rec.Body.String()) req, _ = http.NewRequest(echo.GET, "/", nil) req.Header.Set(echo.AcceptEncoding, "gzip") rec = httptest.NewRecorder() c = echo.NewContext(req, echo.NewResponse(rec), echo.New()) // Gzip Gzip()(h)(c) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding)) assert.Contains(t, rec.Header().Get(echo.ContentType), echo.TextPlain) r, err := gzip.NewReader(rec.Body) defer r.Close() if assert.NoError(t, err) { buf := new(bytes.Buffer) buf.ReadFrom(r) assert.Equal(t, "test", buf.String()) } }
func main() { // Host map hosts := make(Hosts) //----- // API //----- api := echo.New() api.Use(mw.Logger()) api.Use(mw.Recover()) hosts["api.localhost:1323"] = api api.Get("/", func(c *echo.Context) error { return c.String(http.StatusOK, "API") }) //------ // Blog //------ blog := echo.New() api.Use(mw.Logger()) api.Use(mw.Recover()) hosts["blog.localhost:1323"] = blog blog.Get("/", func(c *echo.Context) error { return c.String(http.StatusOK, "Blog") }) //--------- // Website //--------- site := echo.New() site.Use(mw.Logger()) site.Use(mw.Recover()) hosts["localhost:1323"] = site site.Get("/", func(c *echo.Context) error { return c.String(http.StatusOK, "Welcome!") }) http.ListenAndServe(":1323", hosts) }
func TestRemoveTrailingSlash(t *testing.T) { e := echo.New() req, _ := http.NewRequest(echo.GET, "/remove-slash/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := RemoveTrailingSlash()(func(c echo.Context) error { return nil }) h(c) assert.Equal(t, "/remove-slash", req.URL.Path) assert.Equal(t, "/remove-slash", req.RequestURI) // With config req, _ = http.NewRequest(echo.GET, "/remove-slash/?key=value", nil) rec = httptest.NewRecorder() c = e.NewContext(req, rec) h = RemoveTrailingSlashWithConfig(TrailingSlashConfig{ RedirectCode: http.StatusMovedPermanently, })(func(c echo.Context) error { return nil }) h(c) assert.Equal(t, http.StatusMovedPermanently, rec.Code) assert.Equal(t, "/remove-slash?key=value", rec.Header().Get(echo.HeaderLocation)) // With bare URL req, _ = http.NewRequest(echo.GET, "http://localhost", nil) rec = httptest.NewRecorder() c = e.NewContext(req, rec) h = RemoveTrailingSlash()(func(c echo.Context) error { return nil }) h(c) assert.Equal(t, "", req.URL.Path) }
func TestAPIBansakuGetHandler(t *testing.T) { router := echo.New() router.Static("/css", "static/css/api") tmp := p.PrepareTemplates(p.Options{ Directory: "../templates/", Extensions: []string{".tpl"}, }) router.SetRenderer(tmp) router.Get("/api/count", APIBansakuGetHandler) ts := httptest.NewServer(router) defer ts.Close() res, err := http.Get(ts.URL + "/api/count") if err != nil { t.Error("URL is not foung.") } if res.StatusCode != http.StatusOK { t.Error("Status code was wrong.") } defer res.Body.Close() b, err := ioutil.ReadAll(res.Body) if err != nil { t.Error("Can not parse body.") } js, err := simplejson.NewJson(b) if err != nil { t.Error("Can not get json.") } _, err = js.Get("count").Int64() if err != nil { t.Error("Can not get count.") } }
func Server(db *sql.DB) *echo.Echo { dbx := sqlx.NewDb(db, "postgres") e := echo.New() e.Post("/books/:name", createBook(dbx)) e.Get("/books", listBooks(dbx)) return e }
func main() { e := echo.New() e.SetDebug(true) e.Index("public/index.html") e.Post("/upload", upload) e.Run(":1323") }
func StartWebServer() error { conf, err := config.GetConfig() if err != nil { return err } var hystrixTimeout time.Duration conf.Hystrix.Timeout = strings.TrimSpace(conf.Hystrix.Timeout) if conf.Hystrix.Timeout != "" { hystrixTimeout, err = time.ParseDuration(conf.Hystrix.Timeout) if err != nil || hystrixTimeout < time.Millisecond { hystrixTimeout = time.Second log15.Error("Use default time", "module", "hystrix", "timeout", hystrixTimeout) } } hystrix.ConfigureCommand("waitFor", hystrix.CommandConfig{ Timeout: int(int64(hystrixTimeout) / int64(time.Millisecond)), // converted into Millisecond. MaxConcurrentRequests: conf.Hystrix.MaxConcurrentRequests, ErrorPercentThreshold: conf.Hystrix.ErrorPercentThreshold, RequestVolumeThreshold: conf.Hystrix.RequestVolumeThreshold, SleepWindow: conf.Hystrix.SleepWindow, }) e := echo.New() e.Post("/api/v1/tweet", createTweetV1) e.Get("/api/v1/tweets/:id", getAllTweetForV1) e.Get("/api/v1/wait/:timeout", waitFor) e.Get("/api/v1/wait_protected/:timeout", waitForProtected) e.Static("/", "www/static/") logsrv := log15.New("pid", os.Getpid(), "addr", conf.Web.Address) return listenAndServer(logsrv, conf.Web.Address, handlers.LoggingHandler(os.Stdout, handlers.CompressHandler(e.Router()))) }
func BuildEcho() *echo.Echo { // ---------- // Framework // ---------- e := echo.New() // ----------- // Middleware // ----------- e.Use(echo_middleware.Logger()) e.Use(middleware.Recover()) // ------------ // Controllers // ------------ topicsController := new(controllers.TopicsController) // ---------- // Endpoints // ---------- e.Get("/topics", topicsController.Index) e.Get("/topics/:id", topicsController.Show) e.Post("/topics", topicsController.Create) e.Put("/topics/:id", topicsController.Update) e.Delete("/topics/:id", topicsController.Delete) return e }
func main() { // Parse command line arguments kingpin.Version("0.0.1") kingpin.Parse() // Prepare (optionally) embedded resources templateBox := rice.MustFindBox("template") staticHTTPBox := rice.MustFindBox("static").HTTPBox() staticServer := http.StripPrefix("/static/", http.FileServer(staticHTTPBox)) e := echo.New() t := &Template{ templates: template.Must(template.New("base").Parse(templateBox.MustString("base.html"))), } e.SetRenderer(t) e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.GET("/static/*", standard.WrapHandler(staticServer)) edit := e.Group("/edit") edit.Get("/*", EditHandler) edit.Post("/*", EditHandlerPost) go WaitForServer() e.Run(standard.New(fmt.Sprintf("127.0.0.1:%d", *args.Port))) }
func main() { conf.Server = env("SERVER", "127.0.0.1") conf.Password = env("PASSWORD", "ItsPass1942+") conf.User = env("USER", "Administrator") conf.SSHPort = env("SSH_PORT", "22") conf.instDir = os.Getenv("INSTALLATION_DIR") if len(conf.instDir) == 0 { conf.instDir = "/var/lib/nanocloud" } conf.artURL = os.Getenv("ARTIFACT_URL") if len(conf.artURL) == 0 { conf.artURL = "http://releases.nanocloud.org:8080/releases/latest/" } // Echo instance e := echo.New() // Middleware e.Use(mw.Logger()) e.Use(mw.Recover()) h := handler{ iaasCon: iaas.New(conf.Server, conf.Password, conf.User, conf.SSHPort, conf.instDir, conf.artURL), } e.Get("/api/iaas", h.ListRunningVM) e.Post("/api/iaas/:id/stop", h.StopVM) e.Post("/api/iaas/:id/start", h.StartVM) e.Post("/api/iaas/:id/download", h.DownloadVM) e.Run(":8080") }
func TestAddTrailingSlash(t *testing.T) { e := echo.New() req := test.NewRequest(echo.GET, "/add-slash", nil) rec := test.NewResponseRecorder() c := e.NewContext(req, rec) h := AddTrailingSlash()(func(c echo.Context) error { return nil }) h(c) assert.Equal(t, "/add-slash/", req.URL().Path()) assert.Equal(t, "/add-slash/", req.URI()) // With config req = test.NewRequest(echo.GET, "/add-slash?key=value", nil) rec = test.NewResponseRecorder() c = e.NewContext(req, rec) h = AddTrailingSlashWithConfig(TrailingSlashConfig{ RedirectCode: http.StatusMovedPermanently, })(func(c echo.Context) error { return nil }) h(c) assert.Equal(t, http.StatusMovedPermanently, rec.Status()) assert.Equal(t, "/add-slash/?key=value", rec.Header().Get(echo.HeaderLocation)) }
func main() { e := echo.New() e.Use(mw.Logger()) e.Use(mw.Recover()) e.Static("/", "public") e.WebSocket("/ws", func(c *echo.Context) (err error) { ws := c.Socket() msg := "" for { if err = websocket.Message.Send(ws, "Hello, Client!"); err != nil { return } if err = websocket.Message.Receive(ws, &msg); err != nil { return } println(msg) } return }) e.Run(":1323") }
func main() { app := NewApp(nil) defer app.System.DB().Close() for _, db := range app.Store { defer db.DB().Close() } e := echo.New() e.Get("/login", app.Login) e.Get("/logout", app.Logout) s := e.Group("/store") s.Use(Auth(app)) s.Get("/:user", app.List) s.Get("/:user/*", app.Read) s.Post("/:user/*", app.Create) s.Put("/:user/*", app.Update) s.Delete("/:user/*", app.Delete) s.WebSocket("/:user/websocket", app.WebSocket) e.Run(":" + app.Config.Port) }
func main() { // Check for a linked MongoDB container if we are running in Docker mongoHost := os.Getenv("MONGO_PORT_27017_TCP_ADDR") if mongoHost == "" { mongoHost = "localhost" } registerURL := flag.String("registerURL", "", "Register a FHIR Subscription to the specified URL") registerENV := flag.String("registerENV", "", "Register a FHIR Subscription to the the Docker environment variable IE_PORT_3001_TCP*") flag.Parse() parsedURL := *registerURL if parsedURL != "" { registerServer(parsedURL) } if registerENV != nil { registerServer(fmt.Sprintf("http://%s:%s", os.Getenv("IE_PORT_3001_TCP_ADDR"), os.Getenv("IE_PORT_3001_TCP_PORT"))) } e := echo.New() session, err := mgo.Dial(mongoHost) if err != nil { panic("Can't connect to the database") } defer session.Close() basePieURL := discoverSelf() + "pies" db := session.DB("riskservice") svc := service.NewReferenceRiskService(db) svc.RegisterPlugin(assessments.NewCHA2DS2VAScPlugin()) svc.RegisterPlugin(assessments.NewSimplePlugin()) fnDelayer := server.NewFunctionDelayer(3 * time.Second) server.RegisterRoutes(e, db, basePieURL, svc, fnDelayer) e.Use(middleware.Logger()) e.Run(":9000") }
func main() { // Bluemix or local config options -- just local in this repo var port string port = DEFAULT_PORT var host string host = DEFAULT_HOST e := echo.New() // Basic Authentication e.Use(mw.BasicAuth(func(usr, pwd string) bool { if usr == appUser && pwd == appPass { return true } return false })) // Routes e.Post("/send", send) log.Printf("Starting mailservice on %+v:%+v\n", host, port) // Start server e.Run(host + ":" + port) }
// Factory method for application // Makes it possible to do integration testing. func HttpServer() *echo.Echo { // Initialize global syslog logger if l, err := syslog.NewLogger(syslog.LOG_NOTICE|syslog.LOG_LOCAL0, 0); err != nil { panic("gdo: failed to initialize syslog logger: " + err.Error()) } else { logger = l } // Setup middleware e := echo.New() e.Use(middleware.RequestID) // Put that first so loggers can log request id e.Use(em.Logger) // Log to console e.Use(middleware.HttpLogger(logger)) // Log to syslog e.Use(gdm.DOClientInitializer(*dumpFlag)) // Initialize DigitalOcean API client // Setup routes SetupDropletsRoutes(e.Group("/droplets")) SetupDropletActionsRoutes(e.Group("/droplets/:id/actions")) SetupImagesRoutes(e.Group("/images")) SetupImageActionsRoutes(e.Group("/images/:id/actions")) SetupActionsRoutes(e.Group("/actions")) SetupKeysRoutes(e.Group("/keys")) SetupRegionsRoutes(e.Group("/regions")) SetupSizesRoutes(e.Group("/sizes")) // We're done return e }
func main() { e := echo.New() e.SetRenderer(common.Template) common.InitRoutes(e) common.InitPostgres() e.Run(standard.New(":8080")) }
func main() { var err error // Echo instance e := echo.New() e.SetDebug(true) // Middleware e.Use(mw.Logger()) e.Use(mw.Recover()) con, err = sql.Open("mysql", "golang:golang@tcp(localhost:3306)/golang") if err != nil { log.Fatal(err) } data.InitDatabase(con) // createPosts(con) // Routes e.Get("/", hello) // Start server e.Run(":1323") }
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 }
func main() { var ( listen = flag.String("listen", ":3000", "listen address of the application") env = flag.String("env", "dev", "application environment") ) flag.Parse() // set the flags into env vars os.Setenv("APP_ENV", *env) // initialize database connection, with the credentials from the environment. repo, err := database.Connect() if err != nil { panic(err) } // repo configuration repo.LogMode(true) // application configuration router := echo.New() router.SetHTTPErrorHandler(errorHandler) router.Use(middleware.Logger(), middleware.Recover()) registerAuthHandlers(router, handler.AuthService{}) // V1 API endpoints v1 := router.Group("/v1") registerUserHandlers(v1, handler.UserService{repo}) router.Run(*listen) }
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) }
func main() { serv := echo.New() serv.Use(middleware.Logger()) serv.Use(middleware.Recover()) // store := session.NewCookieStore([]byte("secret")) store, err := session.NewRedisStore(32, "tcp", "localhost:6379", "", []byte("secret")) if err != nil { panic(err) } serv.Use(session.Sessions("GSESSION", store)) serv.Get("/", func(ctx echo.Context) error { session := session.Default(ctx) var count int v := session.Get("count") if v == nil { count = 0 } else { count = v.(int) count += 1 } session.Set("count", count) session.Save() ctx.JSON(200, map[string]interface{}{ "visit": count, }) return nil }) serv.Run(standard.New(":8081")) }
func TestListRegions(t *testing.T) { for _, test := range []struct { p mockProvisioner err error code int body string }{ { createProvisioner([]provisioner.Region{}), nil, 200, "[]", }, { createProvisioner([]provisioner.Region{{"name", "description", "country"}}), nil, 200, "[{\"name\":\"name\",\"description\":\"description\",\"country\":\"country\"}]", }, } { s := &yovpnServer{test.p} e := echo.New() req := mustNewRequest("GET", "/regions", nil) w := httptest.NewRecorder() c := echo.NewContext(req, echo.NewResponse(w, e), e) err := s.getRegions(c) assert.Equal(t, test.err, err) assert.Equal(t, test.code, w.Code) assert.Equal(t, test.body, w.Body.String()) } }
func testServer() *httptest.Server { e := echo.New() e.SetRenderer(tmpl.NewRenderer()) // middlewares e.Use(i18n.Langs()) // languages e.Use(flash.Flash()) // flash messages e.Use(userAuth.Normal()) // adding user context data // HOME e.Get("/", base.Home) // AUTH xauth := e.Group("/auth") xauth.Use(csrf.Nosurf()) // csrf protection xauth.Use(csrf.Tokens()) // csrf tokens xauth.Get("/login", Login) xauth.Post("/login", LoginPost) xauth.Get("/register", Register) xauth.Post("/register", RegisterPost) xauth.Get("/logout", Logout) return httptest.NewServer(e) }
func main() { log.Println("Hablo API Service 1.0") // Dial databases, caches, etc. err := managers.Setup() if err != nil { log.Println("Could not start a manager:", err) return } // Configure router e := echo.New() chat.ConfigureHTTPGroup(e.Group("/sockets")) // Add sockets to router profiles.Configure(e.Group("/users")) sessions.Configure(e.Group("/sessions")) settings.Configure(e.Group("/settings")) groups.Configure(e.Group("/groups")) friends.Configure(e.Group("/friends")) // Listen using hostname go e.Run(hostname) // Wait for a interruption signal sigs := make(chan os.Signal) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) log.Println("Terminated by signal:", <-sigs) }
// 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) }
func main() { e := echo.New() // Debug mode e.Debug = true //------------------- // Custom middleware //------------------- // Stats s := NewStats() e.Use(s.Process) e.GET("/stats", s.Handle) // Endpoint to get stats // Server header e.Use(ServerHeader) // Handler e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") }) // Start server e.Logger.Fatal(e.Start(":1323")) }
func main() { e := echo.New() e.Static("/", "./") e.Get("/api", apiHandler) e.Run(":8080") }
func TestLoggerIPAddress(t *testing.T) { e := echo.New() req, _ := http.NewRequest(echo.GET, "/", nil) rec := httptest.NewRecorder() c := echo.NewContext(req, echo.NewResponse(rec, e), e) buf := new(bytes.Buffer) e.Logger().SetOutput(buf) ip := "127.0.0.1" h := func(c *echo.Context) error { return c.String(http.StatusOK, "test") } mw := Logger() // With X-Real-IP req.Header.Add(echo.XRealIP, ip) mw(h)(c) assert.Contains(t, buf.String(), ip) // With X-Forwarded-For buf.Reset() req.Header.Del(echo.XRealIP) req.Header.Add(echo.XForwardedFor, ip) mw(h)(c) assert.Contains(t, buf.String(), ip) // with req.RemoteAddr buf.Reset() mw(h)(c) assert.Contains(t, buf.String(), ip) }
func main() { e := echo.New() e.Debug() //Midleware e.Use(mw.Logger()) e.Use(mw.Recover()) e.SetHTTPErrorHandler(func(err error, c *echo.Context) { log.Println(err) e.DefaultHTTPErrorHandler(err, c) }) //Handlers e.Post("/Plugin.Activate", PluginActivate) e.Post("/NetworkDriver.CreateNetwork", NetworkDriverCreateNetwork) e.Post("/NetworkDriver.DeleteNetwork", NetworkDriverDeleteNetwork) e.Post("/NetworkDriver.CreateEndpoint", NetworkDriverCreateEndpoint) e.Post("/NetworkDriver.EndpointOperInfo", NetworkDriverEndpointOperInfo) e.Post("/NetworkDriver.DeleteEndpoint", NetworkDriverDeleteEndpoint) e.Post("/NetworkDriver.Join", NetworkDriverJoin) e.Post("/NetworkDriver.Leave", NetworkDriverLeave) e.Run(":1313") }