• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang echo.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/labstack/echo.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestGzip

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())
	}
}
开发者ID:alkhatib,项目名称:echo,代码行数:32,代码来源:compress_test.go


示例2: main

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)
}
开发者ID:xyproto,项目名称:echo,代码行数:48,代码来源:server.go


示例3: TestRemoveTrailingSlash

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)
}
开发者ID:luizbafilho,项目名称:fusis,代码行数:35,代码来源:slash_test.go


示例4: TestAPIBansakuGetHandler

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.")
	}
}
开发者ID:Rompei,项目名称:zepher-bansaku,代码行数:34,代码来源:api_controller_test.go


示例5: Server

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
}
开发者ID:caarlos0,项目名称:it,代码行数:7,代码来源:main.go


示例6: StartWebServer

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())))
}
开发者ID:jerome-laforge,项目名称:mytweeter,代码行数:33,代码来源:webwserver.go


示例7: BuildEcho

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
}
开发者ID:gitter-badger,项目名称:burrow,代码行数:32,代码来源:request.go


示例8: main

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)))
}
开发者ID:nochso,项目名称:gomd,代码行数:29,代码来源:gomd.go


示例9: main

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")
}
开发者ID:MeoBlodnasir,项目名称:community,代码行数:34,代码来源:main.go


示例10: TestAddTrailingSlash

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))
}
开发者ID:o1egl,项目名称:echo,代码行数:25,代码来源:slash_test.go


示例11: main

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")
}
开发者ID:ZhiqinYang,项目名称:echo,代码行数:25,代码来源:server.go


示例12: main

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)

}
开发者ID:phrozen,项目名称:rivet,代码行数:25,代码来源:main.go


示例13: main

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")
}
开发者ID:intervention-engine,项目名称:riskservice,代码行数:34,代码来源:server.go


示例14: main

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)

}
开发者ID:olliephillips,项目名称:mailservice,代码行数:28,代码来源:app.go


示例15: HttpServer

// 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
}
开发者ID:cdwilhelm,项目名称:self-service-plugins,代码行数:30,代码来源:main.go


示例16: main

func main() {
	e := echo.New()
	e.SetRenderer(common.Template)
	common.InitRoutes(e)
	common.InitPostgres()
	e.Run(standard.New(":8080"))
}
开发者ID:nathana1,项目名称:FrameworkBenchmarks,代码行数:7,代码来源:main.go


示例17: main

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:[email protected](localhost:3306)/golang")
	if err != nil {
		log.Fatal(err)
	}

	data.InitDatabase(con)

	// createPosts(con)

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

	// Start server
	e.Run(":1323")
}
开发者ID:resetreboot,项目名称:echo_test,代码行数:25,代码来源:server.go


示例18: server

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
}
开发者ID:Xmio,项目名称:intented,代码行数:32,代码来源:main.go


示例19: main

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)
}
开发者ID:twanies,项目名称:gonzo,代码行数:33,代码来源:main.go


示例20: main

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)

}
开发者ID:Dataman-Cloud,项目名称:seckilling,代码行数:26,代码来源:main.go



注:本文中的github.com/labstack/echo.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang echo.NewContext函数代码示例发布时间:2022-05-23
下一篇:
Golang echo.HandlerFunc函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap