Example #1
0
// 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)
}
Example #2
0
func (as ApiService) deleteService(c echo.Context) error {
	if err := as.balancer.DeleteService(c.Param("service_name")); err != nil {
		return err
	}

	return c.NoContent(http.StatusNoContent)
}
Example #3
0
// SetupApp allows the creation of a admin account if no accounts exist.
func SetupApp(c echo.Context) error {
	db := ToDB(c)
	accts, err := db.GetAccountList()
	if len(accts) > 0 || err != nil {
		return ErrForbidden.Log(err, fmt.Sprintf("total accounts: %s", len(accts)))
	}

	p := &Setup{}
	if err := c.Bind(p); err != nil {
		return ErrBind.Log(err)
	}

	p.IsAdmin = true
	if err := db.InsertPerson(&p.Person); err != nil {
		return ErrSaving.Log(err)
	}

	u, _ := model.NewAccountFor(p.PersonID, p.Email)
	if err := u.SetPassword(p.Password); err != nil {
		return ErrPasswordSimple.Log(err)
	}

	u.SetActive()

	if err := db.InsertAccount(u); err != nil {
		return ErrSaving.Log(err)
	}

	return c.NoContent(http.StatusCreated)
}
Example #4
0
func putHandler(c echo.Context) error {
	var val map[string]interface{}

	if err := c.Bind(&val); err != nil {
		return err
	}

	cfg := c.Get("config").(*Config)

	key := c.Param("key")
	obj, err := Put(cfg, key, val)

	if err != nil {
		// Failed validation.
		if errs, ok := err.(ResultErrors); ok {
			return c.JSON(StatusUnprocessableEntity, errs)
		}

		return err
	}

	// No change.
	if obj == nil {
		return c.NoContent(http.StatusNoContent)
	}

	return c.JSON(http.StatusOK, obj)
}
func warmupHandler(c *echo.Context) error {
	if appengine.IsDevAppServer() {
		photographers := []Photographer{
			{1, "Mr Canon"},
			{2, "Miss Nikon"},
			{3, "Mrs Pentax"},
			{4, "Ms Sony"},
		}

		// create some dummy data
		for m := 1; m <= 12; m++ {
			for d := 1; d < 28; d++ {
				taken := time.Date(2015, time.Month(m), d, 12, 0, 0, 0, time.UTC)
				id := rand.Int31n(4)
				photographer := photographers[id]
				p := Photo{
					Photographer: photographer,
					Uploaded:     time.Now().UTC(),
					Width:        8000,
					Height:       6000,
					Taken:        taken,
				}
				k := datastore.NewIncompleteKey(c, "photo", nil)
				nds.Put(c, k, &p)
			}
		}
	}
	return c.NoContent(http.StatusOK)
}
Example #6
0
func CustomHTTPErrorHandler(err error, c echo.Context) {
	code := http.StatusInternalServerError
	response := ErrResponse{}

	switch v := err.(type) {
	case types.ErrNotFound:
		code = http.StatusNotFound
		response = ErrResponse{"error": v.Error()}
	case types.ErrConflict:
		code = http.StatusConflict
		response = ErrResponse{"error": v.Error()}
	case types.ErrValidation:
		code = http.StatusUnprocessableEntity
		response = ErrResponse{"error": v.Errors}
	case *echo.HTTPError:
		response = ErrResponse{"error": v.Message}
	default:
		response = ErrResponse{"error": v.Error()}
	}

	if !c.Response().Committed {
		if c.Request().Method == echo.HEAD { // Issue #608
			c.NoContent(code)
		} else {
			c.JSON(code, response)
		}
	}
}
Example #7
0
// CanSetup returns StatusOK if able to proceed with setup
func CanSetup(c echo.Context) error {
	db := ToDB(c)
	accts, err := db.GetAccountList()
	if len(accts) > 0 || err != nil {
		return ErrForbidden.Log(err, fmt.Sprintf("total accounts: %s", len(accts)))
	}

	return c.NoContent(200)
}
Example #8
0
func CreateCourseTerm(c echo.Context) error {
	courseID, _ := strconv.Atoi(c.Param("courseID"))
	termID, _ := strconv.Atoi(c.Param("termID"))

	db := ToDB(c)
	if err := db.InsertCourseTerm(courseID, termID); err != nil {
		return ErrSaving.Log(err)
	}
	return c.NoContent(http.StatusCreated)
}
func DeleteLanguage(c *echo.Context) error {
	languageId := c.Param("id")

	_, err := db.Exec("DELETE FROM languages WHERE id=$1", languageId)

	if err != nil {
		log.Fatal(err)
	}

	return c.NoContent(http.StatusNoContent)
}
Example #10
0
func getHandler(c echo.Context) error {
	key := c.Param("key")

	vs := c.Param("version")
	ts := c.Param("time")

	cfg := c.Get("config").(*Config)

	obj, err := get(cfg, key, true)

	if err != nil {
		return err
	}

	if vs != "" {
		v, err := strconv.Atoi(vs)

		// Invalid parameter for version, treat as a 404.
		if err != nil {
			return c.NoContent(http.StatusNotFound)
		}

		// Version is greater than what is available.
		if v > obj.Version || v < 0 {
			return c.NoContent(http.StatusNotFound)
		}

		obj = obj.AtVersion(v)
	} else if ts != "" {
		t, err := ParseTimeString(ts)

		// Invalid parameter for version, treat as a 404.
		if err != nil {
			return c.NoContent(http.StatusNotFound)
		}

		obj = obj.AtTime(t)

		if obj == nil {
			return c.NoContent(http.StatusNotFound)
		}
	}

	// Does not exist.
	if obj == nil {
		return c.NoContent(http.StatusNoContent)
	}

	// Do not include history in output.
	obj.History = nil

	return c.JSON(http.StatusOK, obj)
}
Example #11
0
func (ee *EventEndpoints) Delete(c echo.Context) error {
	eventID := c.Param("sg_event_id")

	err := ee.DBAdaptor.DeleteEvent(eventID)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, ControllerError{
			Message: err.Error(),
		})
	}

	return c.NoContent(http.StatusOK)
}
Example #12
0
func (as ApiService) deleteDestination(c echo.Context) error {
	dst, err := as.balancer.GetDestination(c.Param("destination_name"))
	if err != nil {
		return err
	}

	if err := as.balancer.DeleteDestination(dst); err != nil {
		return err
	}

	return c.NoContent(http.StatusNoContent)
}
Example #13
0
func (as ApiService) deleteCheck(c echo.Context) error {
	svcId := c.Param("service_name")
	if _, err := as.balancer.GetService(svcId); err != nil {
		return err
	}

	if err := as.balancer.DeleteCheck(types.CheckSpec{ServiceID: svcId}); err != nil {
		return err
	}

	return c.NoContent(http.StatusNoContent)
}
func (rc *ResourceController) ConditionalDeleteHandler(c *echo.Context) error {
	query := search.Query{Resource: rc.Name, Query: c.Request().URL.RawQuery}
	_, err := rc.DAL.ConditionalDelete(query)
	if err != nil {
		return err
	}

	c.Set("Resource", rc.Name)
	c.Set("Action", "delete")

	c.Response().Header().Set("Access-Control-Allow-Origin", "*")
	return c.NoContent(http.StatusNoContent)
}
Example #15
0
func (s *APIServer) updateFeed(c echo.Context) error {
	b := new(db.FeedInfo)
	err := jsonapi.UnmarshalPayload(c.Request().Body, b)

	if err != nil {
		return newError(c, "Bad Input", err)
	}
	err = s.DBH.SaveFeed(b)
	if err != nil {
		return newError(c, "Error saving Feed", err)
	}
	return c.NoContent(http.StatusNoContent)
}
func (rc *ResourceController) ShowHandler(c *echo.Context) error {
	c.Set("Action", "read")
	_, err := rc.LoadResource(c)
	if err != nil && err != ErrNotFound {
		return err
	}

	c.Response().Header().Set("Access-Control-Allow-Origin", "*")
	if err == ErrNotFound {
		return c.NoContent(http.StatusNotFound)
	}
	return c.JSON(http.StatusOK, c.Get(rc.Name))
}
Example #17
0
// Find one app
func (r App) Get(c *echo.Context, s *dokku.Dokku) error {
	name := c.P(0)

	app, err := s.Apps.Find(name)
	if err != nil {
		return err
	}

	if app == nil {
		return c.NoContent(http.StatusNotFound)
	}

	return c.JSONIndent(http.StatusOK, app, "", "  ")
}
Example #18
0
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
}
func (rc *ResourceController) DeleteHandler(c *echo.Context) error {
	id := c.Param("id")

	if err := rc.DAL.Delete(id, rc.Name); err != nil && err != ErrNotFound {
		return err
	}

	c.Set(rc.Name, id)
	c.Set("Resource", rc.Name)
	c.Set("Action", "delete")

	c.Response().Header().Set("Access-Control-Allow-Origin", "*")
	return c.NoContent(http.StatusNoContent)
}
// Helper function that considers the given *echo.HTTPError and response object and send the appropriate
// HTTP response. The logic is as follows:
// 1. If the *echo.HTTPError is not nil go to 2 else go to 3
// 2. Is the *echo.HTTPError a 404? if yes respond with 404 else respond with 500 and the *echo.HTTPError message
// 3. Is the response object nil? if so respond with given status and empty body else respond with
//    given status and JSON encoded response object.
func RespondStatus(c *echo.Context, status int, respObj interface{}, respErr error) *echo.HTTPError {
	if respErr != nil {
		if godoErr, ok := respErr.(*godo.ErrorResponse); ok {
			if godoErr.Response != nil && godoErr.Response.StatusCode == 404 {
				return c.String(404, http.StatusText(404))
			}
		}
		return c.String(500, respErr.Error())
	}
	if respObj == nil {
		return c.NoContent(status)
	}
	return c.JSON(status, respObj)
}
Example #21
0
File: app.go Project: q1t/movielist
// FIXME reuse user
func (app *App) DeleteList(c *echo.Context) error {
	claims := app.claims(c)
	username := claims["username"].(string)
	user, err := FindUserByUsername(app.DB, username)
	if err != nil {
		return err
	}
	lid, _ := strconv.Atoi(c.Param("id"))
	log.Println(lid)
	if err = user.DeleteList(app.DB, int64(lid)); err != nil {
		return err
	}
	return c.NoContent(http.StatusOK)
}
Example #22
0
// 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)
}
// Handler
func publishMessage(c *echo.Context) error {

	if err := assertContentTypeJSON(c.Request()); err != nil {
		return err
	}

	msg := &message.Message{}
	err := c.Bind(msg)

	if err != nil {
		return echo.NewHTTPError(400, "body content is not in JSON format")
	}

	fmt.Println(msg.ToJSON())

	return c.NoContent(200)
}
Example #24
0
func LanguageDetail(c *echo.Context) error {
	languageId := c.Param("id")

	var language Language

	err := db.QueryRow("SELECT * FROM languages WHERE id =$1", languageId).Scan(&language.Id, &language.Name, &language.Standard)

	if err != nil {
		if err == sql.ErrNoRows {
			return c.NoContent(http.StatusNoContent)
		} else {
			log.Fatal(err)
		}
	}

	return c.JSON(http.StatusOK, language)
}
Example #25
0
func logHandler(c echo.Context) error {
	key := c.Param("key")

	cfg := c.Get("config").(*Config)

	log, err := Log(cfg, key)

	if err != nil {
		return err
	}

	// Does not exist.
	if log == nil {
		return c.NoContent(http.StatusNoContent)
	}

	return c.JSON(http.StatusOK, log)
}
func processPhotosHandler(c *echo.Context) error {
	ctx := appengine.NewContext(c.Request())

	var from time.Time
	var to time.Time
	var err error

	processorName := c.Param("processor")
	fromStr := c.Query("from")
	toStr := c.Query("to")
	now := time.Now().UTC()

	// default to previous day but allow any
	if toStr == "" {
		to = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
	} else {
		to, err = time.Parse(dateFormat, toStr)
		if err != nil {
			log.Errorf(ctx, "to error %s", err.Error())
			return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
		}
	}

	if fromStr == "" {
		from = to.Add(time.Duration(-24) * time.Hour)
	} else {
		from, err = time.Parse(dateFormat, fromStr)
		if err != nil {
			log.Errorf(ctx, "from error %s", err.Error())
			return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
		}
	}

	r := &photoProcessorRange{
		From: from,
		To:   to,
	}
	processorFn := photoProcessors[processorName]
	processor := processorFn(r)
	log.Debugf(c, "%#v", processor)
	processPhotosFunc.Call(ctx, processor)

	return c.NoContent(http.StatusOK)
}
Example #27
0
File: create.go Project: zqzca/back
// Create logs a user in
func (s Controller) Create(e echo.Context) error {
	session := &userSession{}

	if err := e.Bind(session); err != nil {
		return err
	}

	user, err := models.Users(s.DB, qm.Select("hash"), qm.Where("username=$1", session.Username)).One()
	if err != nil {
		s.Error("failed to fetch user", "err", err)
		return e.NoContent(http.StatusInternalServerError)
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(session.Password)); err != nil {
		return e.JSONBlob(http.StatusUnauthorized, errInvalidCredentials)
	}

	return e.NoContent(http.StatusOK)
}
Example #28
0
func ReadCampaign(c *echo.Context) error {
	// GET /campaign/:id
	campaignId := c.Param("id")
	// Get User id from JWT Token

	userid := 5

	var campaign Campaign

	if err := db.QueryRow("SELECT * FROM campaigns WHERE id = $1 AND userid = $2", campaignId, userid).Scan(&campaign.Id, &campaign.UserId, &campaign.Name); err != nil {
		if err == sql.ErrNoRows {
			return c.NoContent(http.StatusNoContent)
		} else {
			log.Fatal(err)
		}
	}

	return c.JSON(http.StatusOK, campaign)
}
Example #29
0
File: p2p.go Project: zqzca/back
// Join does things
func Join(c echo.Context) error {
	id := c.Param("id")

	fmt.Println("sessions", len(api.sessions))
	fmt.Println("id")
	spew.Dump(id)

	fmt.Println("searching..")

	s, ok := api.sessions[id]

	if !ok {
		fmt.Println("failed to find session")
		return c.NoContent(http.StatusNotFound)
	}

	fmt.Println("Found Session with ID:", s.ID)

	return c.JSON(http.StatusOK, s)
}
// callable handler to kick off a processing run
func processHandler(c *echo.Context) error {
	ctx := appengine.NewContext(c.Request())

	name := c.Param("name")
	processorFn, found := processors[name]
	if !found {
		log.Errorf(ctx, "processor %s not found", name)
		return echo.NewHTTPError(http.StatusInternalServerError, "processor not found")
	}

	paramAdapter := newEchoParamAdapter(c)
	processor, err := processorFn(paramAdapter)
	if err != nil {
		log.Errorf(ctx, "error %s", err.Error())
		return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
	}
	processFunc.Call(ctx, processor, "")

	return c.NoContent(http.StatusOK)
}