Exemple #1
0
func Listings(conn *db.Connection) http.Handler {
	return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		if accessToken := req.FormValue("access_token"); accessToken != "" {
			var user models.User
			err := conn.C("users").Find(bson.M{"accesstoken": accessToken}).One(&user)
			if err != nil {
				renderJSON(res, 401, Error{"Bad access token"})
				return
			}

			listings := []models.Listing{}
			err = conn.C("listings").Find(bson.M{"userid": user.Id}).All(&listings)
			if err != nil {
				renderJSON(res, 500, Error{err.Error()})
				return
			}

			renderJSON(res, 200, listings)
		} else {
			lat, err := strconv.ParseFloat(req.FormValue("lat"), 64)
			if err != nil {
				renderJSON(res, 400, Error{err.Error()})
				return
			}
			lng, err := strconv.ParseFloat(req.FormValue("lng"), 64)
			if err != nil {
				renderJSON(res, 400, Error{err.Error()})
				return
			}
			radius, err := strconv.ParseFloat(req.FormValue("radius"), 64)
			if err != nil {
				renderJSON(res, 400, Error{err.Error()})
				return
			}

			listings, err := conn.FindListingsByLocation(lat, lng, radius)
			if err != nil {
				renderJSON(res, 500, Error{err.Error()})
				return
			}

			renderJSON(res, 200, listings)
		}
	})
}