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