Example #1
0
func ListingsHandler(w http.ResponseWriter, r *http.Request) error {
	query, err := util.ValidListingQuery(r.URL) // Returns util.QueryFields
	if err != nil {
		return err
	}

	// Database initialization
	db, err := util.OpenDb()
	if err != nil {
		return err
	}
	defer db.Close()

	listings, err := gen.ReturnListings(db, query.Origin, query.Destination, query.Date+" "+query.Time)
	if err != nil {
		return err
	}
	jsonListings, err := json.MarshalIndent(listings, "", "    ")
	if err != nil {
		return util.NewError(nil, "Json conversion failed", 500)
	}
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprint(w, string(jsonListings))
	return nil
}
Example #2
0
func ListingsHandler(w http.ResponseWriter, r *http.Request) error {
	// Convert POST to GET (also does a time validation)
	if r.FormValue("Origin") != "" || r.FormValue("Destination") != "" {
		convertedDate := ""
		convertedTime := ""
		var err error
		if r.FormValue("Date") == "" {
			convertedDate, convertedTime = util.ReturnCurrentTimeString(true)
		} else if r.FormValue("Time") == "" {
			convertedDate, _, err = util.ReturnTimeString(false, r.FormValue("Date"), "00:00")
			currentDate, currentTime := util.ReturnCurrentTimeString(true)
			if currentDate == convertedDate {
				convertedTime = currentTime
			} else {
				convertedTime = "00:00"
			}
		} else {
			convertedDate, convertedTime, err = util.ReturnTimeString(false, r.FormValue("Date"), r.FormValue("Time"))
			if err != nil {
				return err
			}
		}
		http.Redirect(w, r, "https://5sur.com/l/?o="+r.FormValue("Origin")+"&d="+r.FormValue("Destination")+"&t="+convertedDate+"&h="+convertedTime, 303)
		return nil
	}

	// Query string validation
	query, err := util.ValidListingQuery(r.URL)
	if err != nil {
		return err
	}

	// Database initialization
	db, err := util.OpenDb()
	if err != nil {
		return err
	}
	defer db.Close()

	// User authentication
	user, userId, userImg, err := util.CheckCookie(r, db) // return "" if not logged in
	if err != nil {
		return err
	}

	alerts, err := gen.GetAlerts(db, userId)
	if err != nil {
		return err
	}

	header := &gen.HeaderHTML{
		Title:     "Viajes",
		Username:  user,
		Alerts:    len(alerts),
		AlertText: alerts,
		UserImage: userImg,
	}

	cities, err := gen.ReturnFilter(db)
	if err != nil {
		return err
	}

	listings, err := gen.ReturnListings(db, query.Origin, query.Destination, query.Date+" "+query.Time)
	if err != nil {
		return err
	}

	// Convert date to be human readable
	query.Date, query.Time, err = util.ReturnTimeString(true, query.Date, query.Time)
	if err != nil {
		return err
	}

	body := &gen.ListingsHTML{
		Filter:   cities,
		Listings: listings,
		Query:    query,
	}

	page := struct {
		Header gen.HeaderHTML
		Body   gen.ListingsHTML
	}{
		*header,
		*body,
	}

	err = templates.ExecuteTemplate(w, "listings.html", page)
	if err != nil {
		return util.NewError(err, "No se cargó la página", 500)
	}
	return nil
}