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

Golang echo.HandlerFunc函数代码示例

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

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



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

示例1: echoServer

func echoServer() {
	e := echo.New()
	e.Use(middleware.Logger())
	e.Post("/rsvp", echo.HandlerFunc(requestAddRsvp))

	admin := e.Group("/rsvp")
	admin.Use(middleware.BasicAuth(checkAuth))
	admin.Get("/list", echo.HandlerFunc(requestListRsvp))
	admin.Get("/backup", echo.HandlerFunc(requestBoltBackup))

	e.Static("/", *rootDir)

	fmt.Println("Starting Server:", *httpServ)
	e.Run(standard.New(*httpServ))
}
开发者ID:zacheryph,项目名称:gocode,代码行数:15,代码来源:server.go


示例2: main

func main() {
	// 支持根据参数打印版本信息
	global.PrintVersion(os.Stdout)

	savePid()

	logger.Init(ROOT+"/log", ConfigFile.MustValue("global", "log_level", "DEBUG"))

	go ServeBackGround()

	e := echo.New()

	serveStatic(e)

	e.Use(thirdmw.EchoLogger())
	e.Use(mw.Recover())
	e.Use(pwm.Installed(filterPrefixs))
	e.Use(pwm.HTTPError())
	e.Use(pwm.AutoLogin())

	frontG := e.Group("", thirdmw.EchoCache())
	controller.RegisterRoutes(frontG)

	frontG.GET("/admin", echo.HandlerFunc(admin.AdminIndex), pwm.NeedLogin(), pwm.AdminAuth())
	adminG := e.Group("/admin", pwm.NeedLogin(), pwm.AdminAuth())
	admin.RegisterRoutes(adminG)

	std := standard.New(getAddr())
	std.SetHandler(e)

	gracefulRun(std)
}
开发者ID:studygolang,项目名称:studygolang,代码行数:32,代码来源:main.go


示例3: BasicAuthFromConfig

// BasicAuthFromConfig returns an HTTP basic auth middleware from config.
// See `BasicAuth()`.
func BasicAuthFromConfig(config BasicAuthConfig) echo.MiddlewareFunc {
	return func(next echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			auth := c.Request().Header().Get(echo.Authorization)
			l := len(basic)

			if len(auth) > l+1 && auth[:l] == basic {
				b, err := base64.StdEncoding.DecodeString(auth[l+1:])
				if err == nil {
					cred := string(b)
					for i := 0; i < len(cred); i++ {
						if cred[i] == ':' {
							// Verify credentials
							if config.AuthFunc(cred[:i], cred[i+1:]) {
								return next.Handle(c)
							}
						}
					}
				}
			}
			c.Response().Header().Set(echo.WWWAuthenticate, basic+" realm=Restricted")
			return echo.ErrUnauthorized
		})
	}
}
开发者ID:ggoblin,项目名称:goblin,代码行数:27,代码来源:auth.go


示例4: authorization

// authorization is the authorization middleware for users.
// It checks the access_token in the Authorization header or the access_token query parameter
// On success sets "me" = *User (current logged user) and "accessData" = current access data
// into the context. Sets even the scopes variable, the sorted slice of scopes in accessData
func authorization() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			var accessToken string
			auth := c.Request().Header.Get("Authorization")
			if auth == "" {
				// Check if there's the parameter access_token in the URL
				// this makes the bearer authentication with websockets compatible with OAuth2
				accessToken = c.QueryParam("access_token")
				if accessToken == "" {
					return c.String(http.StatusUnauthorized, "access_token required")
				}
			} else {
				if !strings.HasPrefix(auth, "Bearer ") {
					return echo.ErrUnauthorized
				}
				ss := strings.Split(auth, " ")
				if len(ss) != 2 {
					return echo.ErrUnauthorized
				}
				accessToken = ss[1]
			}

			accessData, err := (&nerdz.OAuth2Storage{}).LoadAccess(accessToken)
			if err != nil {
				return c.String(http.StatusUnauthorized, err.Error())
			}

			// fetch current logged user and store it into the context
			me, err := nerdz.NewUser(accessData.UserData.(uint64))
			if err != nil {
				return c.String(http.StatusInternalServerError, err.Error())
			}
			c.Set("me", me)

			// store the Access Data into the context
			c.Set("accessData", accessData)
			scopes := strings.Split(accessData.Scope, " ")
			sort.Strings(scopes)

			// store the sorted Scopes using the full format
			// eg: if accepted scope is profile:read,write
			// save 2 entries: profile:read and profile:write
			// each saved scope is always in the format <name>:<read|,write>
			var fullScopes []string
			for _, s := range scopes {
				//parts[0] = <scope>, parts[1] = <rw>
				parts := strings.Split(s, ":")
				rw := strings.Split(parts[1], ",")
				for _, perm := range rw {
					fullScopes = append(fullScopes, parts[0]+":"+perm)
				}
			}
			c.Set("scopes", fullScopes)

			// let next handler handle the context
			return next(c)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:64,代码来源:middeleware.go


示例5: GzipFromConfig

// GzipFromConfig return gzip middleware from config.
// See `Gzip()`.
func GzipFromConfig(config GzipConfig) echo.MiddlewareFunc {
	pool := gzipPool(config)
	scheme := "gzip"

	return func(next echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			c.Response().Header().Add(echo.Vary, echo.AcceptEncoding)
			if strings.Contains(c.Request().Header().Get(echo.AcceptEncoding), scheme) {
				rw := c.Response().Writer()
				gw := pool.Get().(*gzip.Writer)
				gw.Reset(rw)
				defer func() {
					if c.Response().Size() == 0 {
						// We have to reset response to it's pristine state when
						// nothing is written to body or error is returned.
						// See issue #424, #407.
						c.Response().SetWriter(rw)
						c.Response().Header().Del(echo.ContentEncoding)
						gw.Reset(ioutil.Discard)
					}
					gw.Close()
					pool.Put(gw)
				}()
				g := gzipResponseWriter{Response: c.Response(), Writer: gw}
				c.Response().Header().Set(echo.ContentEncoding, scheme)
				c.Response().SetWriter(g)
			}
			return next.Handle(c)
		})
	}
}
开发者ID:ggoblin,项目名称:goblin,代码行数:33,代码来源:compress.go


示例6: SetPost

// SetPost is the middleware that checks if the required post, on the project board, exists.
// If it exists, set the "post" = *ProjectPost in the current context
func SetPost() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			var e error
			var pid uint64

			if pid, e = strconv.ParseUint(c.Param("pid"), 10, 64); e != nil {
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: "Invalid post identifier specified",
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			projectID := c.Get("project").(*nerdz.Project).ID()
			var post *nerdz.ProjectPost

			if post, e = nerdz.NewProjectPostWhere(&nerdz.ProjectPost{nerdz.Post{To: projectID, Pid: pid}}); e != nil {
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: "Required post does not exists",
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			c.Set("post", post)
			return next(c)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:36,代码来源:middleware.go


示例7: SetOther

// SetOther is the middleware that sets the context variable "other" to "me"
// therfore we can use the package user methods in the me package
func SetOther() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			c.Set("other", c.Get("me"))
			return next(c)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:10,代码来源:middleware.go


示例8: SetPm

// SetPm is the middleware that check if the required pm exists.
// If it exists, set the "pm" = *Pm in the current context
func SetPm() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {

			// other is the owner of the pm list
			other := c.Get("other").(*nerdz.User)
			// otherID is the ID of the second actor in the conversation
			var otherID, pmID uint64
			var e error
			if otherID, e = strconv.ParseUint(c.Param("other"), 10, 64); e != nil {
				errstr := "Invalid user identifier specified"
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: errstr,
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			if pmID, e = strconv.ParseUint(c.Param("pmid"), 10, 64); e != nil {
				errstr := "Invalid PM identifier specified"
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: errstr,
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			var pm *nerdz.Pm
			if pm, e = nerdz.NewPm(pmID); e != nil {
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: e.Error(),
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			if (pm.From == otherID && pm.To == other.ID()) || (pm.From == other.ID() && pm.To == otherID) {
				c.Set("pm", pm)
				return next(c)
			}

			errstr := "You're not autorized to see the requested PM"
			c.JSON(http.StatusUnauthorized, &rest.Response{
				HumanMessage: errstr,
				Message:      errstr,
				Status:       http.StatusUnauthorized,
				Success:      false,
			})
			return errors.New(errstr)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:60,代码来源:middleware.go


示例9: Mgo

// Mgo returns a middleware which connect to mongo and set the session in the context
func Mgo(mgodb *mgo.Database) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			sc := mgodb.Session.Clone()
			defer sc.Close()
			c.Set("mgok", sc.DB(mgodb.Name))
			return next(c)
		})
	}
}
开发者ID:hexadecy,项目名称:unaframe,代码行数:11,代码来源:mgo.go


示例10: WrapMiddleware

// WrapMiddleware wraps `fasthttp.RequestHandler` into `echo.MiddlewareFunc`
func WrapMiddleware(h fasthttp.RequestHandler) echo.MiddlewareFunc {
	return func(next echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			rq := c.Request().(*Request)
			rs := c.Response().(*Response)
			ctx := rq.RequestCtx
			h(ctx)
			rs.status = ctx.Response.StatusCode()
			rs.size = int64(ctx.Response.Header.ContentLength())
			return next.Handle(c)
		})
	}
}
开发者ID:ggoblin,项目名称:goblin,代码行数:14,代码来源:server.go


示例11: TestRecover

func TestRecover(t *testing.T) {
	e := echo.New()
	buf := new(bytes.Buffer)
	e.SetLogOutput(buf)
	rq := test.NewRequest(echo.GET, "/", nil)
	rc := test.NewResponseRecorder()
	c := e.NewContext(rq, rc)
	h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
		panic("test")
	}))
	h(c)
	assert.Equal(t, http.StatusInternalServerError, rc.Status())
	assert.Contains(t, buf.String(), "PANIC RECOVER")
}
开发者ID:caiqfrog,项目名称:echo,代码行数:14,代码来源:recover_test.go


示例12: TestRecover

func TestRecover(t *testing.T) {
	e := echo.New()
	buf := new(bytes.Buffer)
	e.Logger.SetOutput(buf)
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)
	h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
		panic("test")
	}))
	h(c)
	assert.Equal(t, http.StatusInternalServerError, rec.Code)
	assert.Contains(t, buf.String(), "PANIC RECOVER")
}
开发者ID:luizbafilho,项目名称:fusis,代码行数:14,代码来源:recover_test.go


示例13: SetProject

// SetProject is the middleware that checks if the current logged user can see the required project
// and if the required project exists. On success sets the "project" = *Project variable in the context
func SetProject() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			var project *nerdz.Project
			var err error
			if project, err = rest.Project("id", c); err != nil {
				return err
			}
			// store the project Project into the context
			c.Set("project", project)
			// pass context to the next handler
			return next(c)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:17,代码来源:middleware.go


示例14: SetComment

// SetComment is the middleware that check if the required comment, on the user board, exists.
// If it exists, set the "comment" =  *UserPostComment in the current context
func SetComment() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {

			var cid uint64
			var e error
			if cid, e = strconv.ParseUint(c.Param("cid"), 10, 64); e != nil {
				errstr := "Invalid comment identifier specified"
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: errstr,
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			var comment *nerdz.UserPostComment
			if comment, e = nerdz.NewUserPostComment(cid); e != nil {
				errstr := "Invalid comment identifier specified"
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: errstr,
					Message:      e.Error(),
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}

			post := c.Get("post").(*nerdz.UserPost)
			if comment.Hpid != post.Hpid {
				errstr := "Mismatch between comment ID and post ID. Comment not related to the post"
				c.JSON(http.StatusBadRequest, &rest.Response{
					HumanMessage: errstr,
					Message:      errstr,
					Status:       http.StatusBadRequest,
					Success:      false,
				})
				return e
			}
			c.Set("comment", comment)
			return next(c)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:47,代码来源:middleware.go


示例15: setPmsOptions

// setPmsOptions is the middleware that sets the "pmsOptions" = *nerdz.PmsOptions into the current context
// handle GET parameters:
func setPmsOptions() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			old := c.QueryParam("older")
			new := c.QueryParam("newer")

			older, _ := strconv.ParseUint(old, 10, 64)
			newer, _ := strconv.ParseUint(new, 10, 64)

			n, _ := strconv.ParseUint(c.QueryParam("n"), 10, 8)

			c.Set("pmsOptions", &nerdz.PmsOptions{
				N:     nerdz.AtMostComments(n),
				Older: older,
				Newer: newer,
			})
			return next(c)
		})
	}
}
开发者ID:nerdzeu,项目名称:nerdz-api,代码行数:22,代码来源:middeleware.go


示例16: TransactionHandler

func TransactionHandler(db *dbr.Session) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			tx, _ := db.Begin()

			c.Set(TxKey, tx)

			if err := next(c); err != nil {
				tx.Rollback()
				logrus.Debug("Transction Rollback: ", err)
				return err
			}

			logrus.Debug("Transction Commit")
			tx.Commit()

			return nil
		})
	}
}
开发者ID:suzumi,项目名称:snicket,代码行数:20,代码来源:transaction.go


示例17: StoreHeaders

// StoreHeaders get header values and set to context
func StoreHeaders(options ...*StoreHeaderOptions) echo.MiddlewareFunc {
	return func(next echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			request := c.Request()
			header := request.Header()
			url := request.URL()

			//application/vnd.get3w.v3+json
			version := VersionV1
			accept := header.Get("Accept")
			if accept == "" || accept == "application/vnd.get3w.v1+json" {
				version = VersionV1
			}
			c.Set("Version", version)

			auth := header.Get("Authorization")
			l := len(Bearer)
			accessToken := ""

			if len(auth) > l+1 && auth[:l] == Bearer {
				accessToken = auth[l+1:]
			} else if len(header.Get(TokenNameOfHeader)) > 0 {
				accessToken = header.Get(TokenNameOfHeader)
			} else if len(url.QueryValue(TokenNameOfQuery)) > 0 {
				accessToken = url.QueryValue(TokenNameOfQuery)
			}

			c.Set("AccessToken", accessToken)

			config, _ := home.LoadConfig()
			c.Set("Config", config)

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

			return nil
		})
	}
}
开发者ID:get3w,项目名称:get3w,代码行数:41,代码来源:api.go


示例18: Modify

// Modify 编辑规则
func (self RuleController) Modify(ctx echo.Context) error {
	var data = make(map[string]interface{})

	if ctx.FormValue("submit") == "1" {
		user := ctx.Get("user").(*model.Me)

		errMsg, err := logic.DefaultRule.Save(ctx, ctx.FormParams(), user.Username)
		if err != nil {
			return fail(ctx, 1, errMsg)
		}
		return success(ctx, nil)
	}

	rule := logic.DefaultRule.FindById(ctx, ctx.QueryParam("id"))
	if rule == nil {
		return ctx.Redirect(http.StatusSeeOther, ctx.Echo().URI(echo.HandlerFunc(self.RuleList)))
	}

	data["rule"] = rule

	return render(ctx, "rule/modify.html", data)
}
开发者ID:studygolang,项目名称:studygolang,代码行数:23,代码来源:rule.go


示例19: Modify

// Modify
func (self ArticleController) Modify(ctx echo.Context) error {
	var data = make(map[string]interface{})

	if ctx.FormValue("submit") == "1" {
		user := ctx.Get("user").(*model.Me)
		errMsg, err := logic.DefaultArticle.Modify(ctx, user, ctx.FormParams())
		if err != nil {
			return fail(ctx, 1, errMsg)
		}
		return success(ctx, nil)
	}
	article, err := logic.DefaultArticle.FindById(ctx, ctx.QueryParam("id"))
	if err != nil {
		return ctx.Redirect(http.StatusSeeOther, ctx.Echo().URI(echo.HandlerFunc(self.ArticleList)))
	}

	data["article"] = article
	data["statusSlice"] = model.ArticleStatusSlice
	data["langSlice"] = model.LangSlice

	return render(ctx, "article/modify.html", data)

}
开发者ID:studygolang,项目名称:studygolang,代码行数:24,代码来源:article.go


示例20: RecoverFromConfig

// RecoverFromConfig returns a recover middleware from config.
// See `Recover()`.
func RecoverFromConfig(config RecoverConfig) echo.MiddlewareFunc {
	return func(next echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			defer func() {
				if r := recover(); r != nil {
					var err error
					switch r := r.(type) {
					case error:
						err = r
					default:
						err = fmt.Errorf("%v", r)
					}
					stack := make([]byte, config.StackSize)
					length := runtime.Stack(stack, config.StackAll)
					if config.PrintStack {
						c.Logger().Printf("[%s] %s %s", color.Red("PANIC RECOVER"), err, stack[:length])
					}
					c.Error(err)
				}
			}()
			return next.Handle(c)
		})
	}
}
开发者ID:ggoblin,项目名称:goblin,代码行数:26,代码来源:recover.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang echo.New函数代码示例发布时间:2022-05-23
下一篇:
Golang plugins.BotEvent类代码示例发布时间: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