本文整理汇总了Golang中github.com/labstack/echo.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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())
}
}
示例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)
}
示例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)
}
示例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.")
}
}
示例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
}
示例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())))
}
示例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
}
示例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)))
}
示例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")
}
示例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))
}
示例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")
}
示例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)
}
示例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")
}
示例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)
}
示例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
}