当前位置: 首页>>代码示例>>Golang>>正文


Golang echo.HandlerFunc函数代码示例

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


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


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