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

Golang echo.NewHTTPError函数代码示例

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

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



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

示例1: ArchiveView

// ArchiveView shows a list of posts arranged by its date
func ArchiveView(c *echo.Context) error {
	id := c.Param("id")
	var err error

	// Get archive data
	var archive models.Archive
	err = database.Current.Get(&archive, database.Queries.ArchiveBySignature, id)
	if err != nil {
		log.Println("Cannot get archive by signature", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Get related posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.ArchiveAuthoredPosts, id)
	if err != nil {
		log.Println("Cannot select posts", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Create our render context and fill base data
	ac := archiveContext{
		Archive:      archive,
		RelatedPosts: posts,
	}

	err = fillBlogContext(c, &ac.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	return c.Render(200, "archive", ac)
}
开发者ID:cedmundo,项目名称:site,代码行数:35,代码来源:handlers.go


示例2: putPlace

// putPlace изменяет определение уже существующего места.
func putPlace(c *echo.Context) error {
	groupID := c.Get("GroupID").(string)
	placeID := c.Query("place-id")
	if !bson.IsObjectIdHex(placeID) {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	var place places.Place // описание места
	err := c.Bind(&place)  // разбираем описание места из запроса
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if place.Circle == nil && place.Polygon == nil {
		return echo.NewHTTPError(http.StatusBadRequest)
	}
	place.ID = bson.ObjectIdHex(placeID)
	place.GroupID = groupID
	_, err = placesDB.Save(place)
	if err == mgo.ErrNotFound {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	if err != nil {
		llog.Error("placesDB error: %v", err)
		return err
	}
	return c.NoContent(http.StatusOK)
}
开发者ID:jtprog,项目名称:geotrack,代码行数:27,代码来源:places.go


示例3: auth

// auth является вспомогательной функцией, проверяющей и разбирающей токен с авторизационной
// информацией в HTTP-заголовке. Разобранная информация сохраняется в контексте запроса.
func auth(h echo.HandlerFunc) echo.HandlerFunc {
	return func(c *echo.Context) error {
		req := c.Request()                                  // получаем доступ к HTTP-запросу
		if req.Header.Get(echo.Upgrade) == echo.WebSocket { // пропускаем запросы WebSocket
			return nil
		}
		data, err := tokenEngine.ParseRequest(req) // разбираем токен из запроса
		if err != nil {
			llog.Warn("Bad token: %v", err)
			return echo.NewHTTPError(http.StatusForbidden)
		}
		groupID := data["group"].(string)
		userID := data["id"].(string)
		if !bson.IsObjectIdHex(userID) {
			llog.Warn("Bad user Object ID: %v", userID)
			return echo.NewHTTPError(http.StatusForbidden)
		}
		userObjectId := bson.ObjectIdHex(userID)
		// проверяем, что пользователь есть и входит в эту группу
		exists, err := usersDB.Check(groupID, userObjectId)
		if err != nil {
			llog.Error("usersDB error: %v", err)
			return err
		}
		if !exists {
			llog.Debug("Auth not exist: %v (%v)", userID, groupID)
			return echo.NewHTTPError(http.StatusForbidden)
		}
		c.Set("GroupID", groupID) // сохраняем данные в контексте запроса
		c.Set("ID", userObjectId)
		llog.Debug("Auth: %v (%v)", userID, groupID)
		return h(c) // выполняем основной обработчик
	}
}
开发者ID:jtprog,项目名称:geotrack,代码行数:36,代码来源:login.go


示例4: postDevicePairing

func postDevicePairing(c *echo.Context) error {
	groupID := c.Get("GroupID").(string)
	deviceID := c.Param("device-id")
	_, _ = groupID, deviceID
	var pairingKey struct {
		Key string
	}
	err := c.Bind(&pairingKey) // читаем ключ из запроса
	if err != nil || len(pairingKey.Key) < 4 {
		return echo.NewHTTPError(http.StatusBadRequest)
	}
	var deviceIDResp string
	err = nce.Request(serviceNamePairingKey, pairingKey.Key, &deviceIDResp, natsRequestTimeout)
	if err != nil {
		llog.Error("NATS Pairing Key response error: %v", err)
		return err
	}
	if deviceIDResp == "" {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	if deviceIDResp == deviceID {
		// TODO: реально связать в базе
		return echo.NewHTTPError(http.StatusOK)
	}
	if deviceID == "" {
		return c.JSON(http.StatusOK, map[string]string{"ID": deviceIDResp})
	}
	return echo.NewHTTPError(http.StatusBadRequest)
}
开发者ID:jtprog,项目名称:geotrack,代码行数:29,代码来源:devices.go


示例5: Auth

// Authentication middleware using Session Tokens, every request handled is checked
// for the X-Session-Token Header, decodes the session and authenticates the user to
// it's resources in the store. Returns [400] for a bad token, [401] for non valid
// sessions, and proceeds with request otherwise.
func Auth(app *App) echo.HandlerFunc {

	return func(c *echo.Context) error {
		//Check for session token
		header := c.Request().Header.Get("X-Session-Token")

		// If no token [401], should login
		if header == "" {
			return echo.NewHTTPError(http.StatusUnauthorized)
		}

		// Token cannot be decoded or mismatch token length [400]
		// Session Tokens are 32 bytes long (64 hexadecimal characters)
		token, err := hex.DecodeString(header)
		if err != nil || len(token) != 32 {
			return echo.NewHTTPError(http.StatusBadRequest)
		}

		// If Session Token is not found (maybe no longer valid due to logout)
		// client gets [401] should login again
		session := app.System.Get("session", c.Param("user"))
		if session == nil {
			return echo.NewHTTPError(http.StatusUnauthorized)
		}

		// Finally if tokens don't match [401]
		if string(token) != string(session) {
			return echo.NewHTTPError(http.StatusUnauthorized)
		}

		return nil
	}

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


示例6: ApiNextTaskHandler

// ApiNextTaskHandler implements method for getting next task from the queue
func (h *handler) ApiNextTaskHandler(c *echo.Context) error {

	enc := json.NewDecoder(c.Request().Body)

	var taskReq common.TaskRequest
	if err := enc.Decode(&taskReq); err != nil {
		c.Request().Body.Close()
		return echo.NewHTTPError(http.StatusBadRequest, "Wrong JSON. Expected gobench.common.TaskRequest")
	}

	c.Request().Body.Close()

	// checks existing test environment by authKey received by client
	ok, err := h.back.Model.TestEnvironment.Exist(taskReq.AuthKey)
	if err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	if !ok {
		return echo.NewHTTPError(http.StatusBadRequest, "Wrong authKey!")
	}

	// retrives single task
	taskRow, err := h.back.Model.Task.Next(taskReq.AuthKey)
	if err != nil {
		if err == model.ErrNotFound {
			return echo.NewHTTPError(http.StatusNoContent)
		}
		return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
	}

	task := common.TaskResponse{Id: taskRow.Id.Hex(), PackageName: taskRow.PackageName, Type: []string{"benchmark"}}

	return c.JSON(http.StatusOK, task)
}
开发者ID:goben-ch,项目名称:gobench,代码行数:36,代码来源:bencher.go


示例7: CategoryView

// CategoryView shows a list of posts arranged by its category
func CategoryView(c *echo.Context) error {
	// Parse pagination attributes
	pn, ps := utils.GetPage(c)
	id, _ := strconv.Atoi(c.Param("id"))

	// Get category using id
	var category models.Category
	err := database.Current.Get(&category, database.Queries.CategoryByID, id)
	if err != nil {
		log.Println("Cannot select category:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Query the posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.AuthoredPostsByCategory, id, ps, ps*(pn-1))
	if err != nil {
		log.Println("Cannot select posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var count int
	err = database.Current.Get(&count, database.Queries.PostByCategoryCount, id)
	if err != nil {
		log.Println("Cannot count posts:", err)
	}

	pc := int(math.Floor(float64(count/ps))) + 1

	// Generate preview for all posts
	for _, p := range posts {
		p.Preview = createPreview(p.TextContent)
	}

	// Create our context and fill base data
	cc := categoryContext{
		Category: category,
		RelatedPosts: models.Paginated{
			TotalObjects:  count,
			PageCount:     pc,
			PageNumber:    pn,
			PageSize:      ps,
			NextAvailable: pn < pc,
			Results:       posts,
		},
	}

	err = fillBlogContext(c, &cc.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Render the results
	return c.Render(200, "category", cc)
}
开发者ID:cedmundo,项目名称:site,代码行数:57,代码来源:handlers.go


示例8: Error

// Error forwards to echo.Error
func (e *echoHandler) Error(c server.Context, code int, d ...interface{}) error {
	switch v := d[0].(type) {
	case error:
		return echo.NewHTTPError(code, v.Error())
	case string:
		return echo.NewHTTPError(code, v)
	default:
		return echo.NewHTTPError(code)
	}
}
开发者ID:pedronasser,项目名称:garf,代码行数:11,代码来源:response.go


示例9: Upload

func (s *FilesService) Upload(params url.Values) *Responder {

	var (
		err error
	)
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	for k, values := range params {
		switch k {
		default:
			err = writer.WriteField(k, values[0])
			if err != nil {
				return &Responder{
					Error: echo.NewHTTPError(http.StatusBadRequest, err.Error()),
				}
			}
		case "file":
			for _, path := range values {
				file, err := os.Open(path)
				if err != nil {
					return &Responder{
						Error: echo.NewHTTPError(http.StatusBadRequest, err.Error()),
					}
				}
				defer file.Close()
				part, err := writer.CreateFormFile("file", filepath.Base(path))
				if err != nil {
					return &Responder{
						Error: echo.NewHTTPError(http.StatusBadRequest, err.Error()),
					}
				}
				_, err = io.Copy(part, file)
				if err != nil {
					return &Responder{
						Error: echo.NewHTTPError(http.StatusBadRequest, err.Error()),
					}
				}
			}
		}
	}
	defer writer.Close()
	return &Responder{
		Body: body,
		Headers: map[string]string{
			"Content-Type": writer.FormDataContentType(),
		},
		Method:  "MULTIPART",
		Params:  params,
		Rpc:     "upload",
		Service: s,
	}
}
开发者ID:laicosly,项目名称:go-social-slack,代码行数:52,代码来源:files.go


示例10: HMACAuth

func HMACAuth(o *HmacOpts) echo.HandlerFunc {
	return func(c *echo.Context) error {
		auth, err := newAuth(c.Request(), o)
		if nil != err {
			return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
		}
		if err := auth.Authentic(c.Request()); nil != err {
			return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
		}
		c.Set(API_KEY, auth.ApiKey)
		return nil
	}
}
开发者ID:glennsb,项目名称:atm,代码行数:13,代码来源:hmac_auth.go


示例11: Login

// Login route (/login), credentials are given as Basic Authentication, so be sure to do it over SSL or private networking.
// If authentication is successful, it returns [200] and a 32 byte X-Session-Token in a hex encoded string.
// All authenticated requests should include the X-Session-Token header with this value, if the token is no longer
// valid due to logout or expiration, a [401] usually means you have to call this login endpoint again and obtain a new token.
func (app *App) Login(c *echo.Context) error {
	//Check for Basic Authentication Header
	user, pass, ok := c.Request().BasicAuth()
	if !ok {
		return echo.NewHTTPError(http.StatusBadRequest)
	}
	// If credentials don't match
	if !app.Authenticate(user, pass) {
		return echo.NewHTTPError(http.StatusUnauthorized)
	}
	// Return either a new Session Token or an existing one
	return c.String(http.StatusOK, app.NewSession(user))
}
开发者ID:phrozen,项目名称:rivet,代码行数:17,代码来源:auth.go


示例12: deleteEndpoint

func (s *yovpnServer) deleteEndpoint(c *echo.Context) error {
	id := c.Param("id")
	if len(id) == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "ID not provided!")
	}

	_, err := s.provisioner.DestroyEndpoint(id)
	if err != nil {
		return echo.NewHTTPError(http.StatusNotFound, "Endpoint not found!")
	}

	c.NoContent(http.StatusNoContent)
	return nil
}
开发者ID:xperimental,项目名称:yovpn,代码行数:14,代码来源:web.go


示例13: getEndpoint

func (s *yovpnServer) getEndpoint(c *echo.Context) error {
	id := c.Param("id")
	if len(id) == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "ID not provided!")
	}

	endpoint, err := s.provisioner.GetEndpoint(id)
	if err != nil {
		return echo.NewHTTPError(http.StatusNotFound, "Endpoint not found!")
	}

	c.JSON(http.StatusOK, endpoint)
	return nil
}
开发者ID:xperimental,项目名称:yovpn,代码行数:14,代码来源:web.go


示例14: ProfileView

// ProfileView renders the profile data with the fancy portfolio template
func ProfileView(c *echo.Context) error {
	id := c.Param("id") // ID in this case applies to username
	var err error

	var profile models.Profile
	err = database.Current.Get(&profile, database.Queries.ProfileByUsername, id)
	if err != nil {
		log.Println("Cannot get profile:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var skills []models.ResumeSkill
	err = database.Current.Select(&skills, database.Queries.ResumeSkillsByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot get skills:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var jobs []models.ResumeJob
	err = database.Current.Select(&jobs, database.Queries.ResumeJobsByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot select jobs:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var education []models.ResumeEducation
	err = database.Current.Select(&education, database.Queries.ResumeEducationByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot select education:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var projects []models.ResumeProject
	err = database.Current.Select(&projects, database.Queries.ResumeProjectsByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot select projects:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	pc := profileContext{
		Profile:   profile,
		Skills:    skills,
		Jobs:      jobs,
		Education: education,
		Projects:  projects,
	}

	return c.Render(200, "profile", pc)
}
开发者ID:cedmundo,项目名称:site,代码行数:50,代码来源:handlers.go


示例15: Index

// Index serves blog index view
func Index(c *echo.Context) error {

	// Parse pagination attributes
	pn, ps := utils.GetPage(c)

	// Query the posts
	var posts []models.AuthoredPost
	err := database.Current.Select(&posts, database.Queries.AuthoredPosts, ps, ps*(pn-1))
	if err != nil {
		log.Println("Cannot select posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var count int
	err = database.Current.Get(&count, database.Queries.PostCount)
	if err != nil {
		log.Println("Cannot count posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	pc := int(math.Floor(float64(count/ps))) + 1

	// Generate preview for all posts
	for _, p := range posts {
		p.Preview = createPreview(p.TextContent)
	}

	// Create our render context and fill base data
	ic := indexContext{
		PostResults: models.Paginated{
			TotalObjects:  count,
			PageCount:     pc,
			PageNumber:    pn,
			PageSize:      ps,
			NextAvailable: pn < pc,
			Results:       posts,
		},
	}

	err = fillBlogContext(c, &ic.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Render the results
	return c.Render(200, "index", ic)
}
开发者ID:cedmundo,项目名称:site,代码行数:49,代码来源:handlers.go


示例16: JobsNewPost

// JobsNewPost process the new job form.
//
//		Method           POST
//
//		Route            /dash/jobs/new
//
//		Restrictions     Yes
//
// 		Template         None
func JobsNewPost(ctx *echo.Context) error {
	var flashMessages = flash.New()
	f := forms.New(utils.GetLang(ctx))
	jf := f.JobForm()(ctx.Request())
	if !jf.IsValid() {
		// TODO: improve flash message ?
		flashMessages.Err(msgInvalidorm)
		flashMessages.Save(ctx)
		ctx.Redirect(http.StatusFound, "/dash/jobs/new")
		return nil
	}

	if isLoged := ctx.Get("IsLoged"); isLoged != nil {
		person := ctx.Get("User").(*models.Person)
		if jerr := query.PersonCreateJob(person, jf.GetModel().(forms.JobForm)); jerr != nil {
			// TODO: improve flash message ?
			flashMessages.Err("some really bad fish happened")
			flashMessages.Save(ctx)
			ctx.Redirect(http.StatusFound, "/dash/jobs/new")
			return nil
		}
		// add flash message
		flashMessages.Success("new job was created successful")
		flashMessages.Save(ctx)

		ctx.Redirect(http.StatusFound, "/dash/")
		return nil
	}
	he := echo.NewHTTPError(http.StatusUnauthorized)
	ctx.Error(he)
	return nil
}
开发者ID:jwulf,项目名称:zedlist,代码行数:41,代码来源:dashboard.go


示例17: BasicAuth

func BasicAuth() echo.HandlerFunc {
	return func(c *echo.Context) error {
		// Skip WebSocket
		if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
			return nil
		}

		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
						for _, d := range conf.Domains {
							if cred[:i] == d.Name && bcrypt.CompareHashAndPassword([]byte(d.PassHash), []byte(cred[i+1:])) == nil {
								c.Set("domain", d)
								return nil
							}
						}
					}
				}
			}
		}
		c.Response().Header().Set(echo.WWWAuthenticate, Basic+" realm=Restricted")
		return echo.NewHTTPError(http.StatusUnauthorized)
	}
}
开发者ID:fazalmajid,项目名称:postmapweb,代码行数:31,代码来源:postmapweb.go


示例18: JWTAuth

// JWTAuth returns a JWT authentication middleware.
//
// For valid token it sets JWT claims in the context with key `_claims` and calls
// the next handler.
// For invalid Authorization header it sends "404 - Bad Request" response.
// For invalid credentials, it sends "401 - Unauthorized" response.
func JWTAuth(fn JWTValidateFunc) echo.HandlerFunc {
	return func(c *echo.Context) error {
		// Skip WebSocket
		if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
			return nil
		}

		auth := c.Request().Header.Get("Authorization")
		l := len(Bearer)
		he := echo.NewHTTPError(http.StatusBadRequest)

		if len(auth) > l+1 && auth[:l] == Bearer {
			t, err := jwt.Parse(auth[l+1:], func(token *jwt.Token) (interface{}, error) {
				// Lookup key and verify method
				if kid := token.Header["kid"]; kid != nil {
					return fn(kid.(string), token.Method)
				}
				return fn("", token.Method)
			})
			if err == nil && t.Valid {
				c.Set("_claims", t.Claims)
				return nil
			} else {
				he.SetCode(http.StatusUnauthorized)
			}
		}
		return he
	}
}
开发者ID:jimwei,项目名称:photoswall,代码行数:35,代码来源:auth.go


示例19: JWTAuth

func JWTAuth(key string) echo.HandlerFunc {
	return func(c *echo.Context) error {

		// Skip WebSocket
		if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
			return nil
		}

		auth := c.Request().Header.Get("Authorization")
		l := len(Bearer)
		halt := echo.NewHTTPError(http.StatusUnauthorized)

		if len(auth) > l+1 && auth[:l] == Bearer {
			t, err := jwt.Parse(auth[l+1:], func(token *jwt.Token) (interface{}, error) {

				// Always check the signing method
				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
					return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
				}

				// Return the key for validation
				return []byte(key), nil
			})
			if err == nil && t.Valid {
				// Store token claims in echo.Context
				c.Set("claims", t.Claims)
				return nil
			}
		}
		return halt
	}
}
开发者ID:q1t,项目名称:movielist,代码行数:32,代码来源:auth.go


示例20: deletePlace

// deletePlace удаляет определение места.
func deletePlace(c *echo.Context) error {
	groupID := c.Get("GroupID").(string)
	placeID := c.Query("place-id")
	if !bson.IsObjectIdHex(placeID) {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	err := placesDB.Delete(groupID, bson.ObjectIdHex(placeID))
	if err == mgo.ErrNotFound {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	if err != nil {
		llog.Error("placesDB error: %v", err)
		return err
	}
	return c.NoContent(http.StatusOK)
}
开发者ID:jtprog,项目名称:geotrack,代码行数:17,代码来源:places.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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