func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	brand := vars["brand"]
	postalCode := vars["postalCode"]

	tracelog.Trace("Brand Value", "main", "Brand is %s", brand)
	tracelog.Trace("Postal Code", "main", "PostalCode is %s", postalCode)

	// now call the Edmunds API
	dealers, dealerErr := DealersAroundZipCode(postalCode, 100, brand, true)
	if dealerErr != nil {
		ReturnErrorToClient(w, dealerErr, "Error calling dealer service with zip code "+postalCode)
		tracelog.Error(dealerErr, "DealersAroundZipCode failed", "HomeHandler")
		return
	}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(dealers); err != nil {
		tracelog.Error(err, "JSON encoding failed", "HomeHandler")
		panic(err)
	}
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	lat := vars["lat"]
	lng := vars["lng"]
	distance := vars["distance"]

	tracelog.Trace("Latitude", "main", "Lat is %s", lat)
	tracelog.Trace("Longitude", "main", "Lng is %s", lng)
	tracelog.Trace("Distance", "main", "Distance is %s", distance)

	// call the GasFeed API

	stations, stationErr := NearbyGasStations(lat, lng, distance)
	if stationErr != nil {
		ReturnErrorToClient(w, stationErr, "Error calling gas station pricing service with lat "+lat+" lng "+lng+" and distance "+distance)
		tracelog.Error(stationErr, "NearbyGasStations failed", "HomeHandler")
		return
	}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(stations); err != nil {
		tracelog.Error(err, "JSON encoding failed", "HomeHandler")
		panic(err)
	}
}
func ReturnErrorToClient(w http.ResponseWriter, err error, msg string) {
	tracelog.Error(err, msg, "ReturnErrorToClient")

	w.WriteHeader(http.StatusBadRequest)

	if encodeError := json.NewEncoder(w).Encode(JsonError{Code: http.StatusBadRequest, Error: msg}); encodeError != nil {
		tracelog.Error(encodeError, "JSON encoding failed", "ReturnErrorToClient")
		panic("JSON encoding failed")
	}
}
Beispiel #4
0
func AddBook(jsonStr []byte) bool {
	o := orm.NewOrm()
	var book Book
	err := json.Unmarshal(jsonStr, &book)
	if err != nil {
		tracelog.Error(err, "Failed to insert json", "model.AddBook")
		return false
	}
	_, err = o.Insert(&book)
	if err != nil {
		tracelog.Error(err, "Failed to insert book", "model.AddBook")
		return false
	}
	return true
}
Beispiel #5
0
func UpdateLibrary(jsonStr []byte) bool {
	o := orm.NewOrm()
	var lib Library
	err := json.Unmarshal(jsonStr, &lib)
	if err != nil {
		tracelog.Error(err, "Failed to parse json", "model.UpdateLibrary")
		return false
	}
	_, err = o.Update(&lib)
	if err != nil {
		tracelog.Error(err, "Failed to update lib", "model.UpdateLibrary")
		return false
	}
	return true
}
Beispiel #6
0
func AddLibrary(jsonStr []byte) bool {
	o := orm.NewOrm()
	var lib Library
	err := json.Unmarshal(jsonStr, &lib)
	if err != nil {
		tracelog.Error(err, "Failed to insert json", "model.AddLibrary")
		return false
	}
	_, err = o.Insert(&lib)
	if err != nil {
		tracelog.Error(err, "Failed to insert lib", "model.AddLibrary")
		return false
	}
	return true
}
Beispiel #7
0
func UpdateBook(jsonStr []byte) bool {
	o := orm.NewOrm()
	var book Book
	err := json.Unmarshal(jsonStr, &book)
	if err != nil {
		tracelog.Error(err, "Failed to parse json", "model.UpdateBook")
		return false
	}
	_, err = o.Update(&book)
	if err != nil {
		tracelog.Error(err, "Failed to update book", "model.UpdateBook")
		return false
	}
	return true
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	lat, latErr := strconv.ParseFloat(vars["lat"], 32)
	if latErr != nil {
		ReturnErrorToClient(w, latErr, "Invalid latitude value. Expecting a floating point number")
		return
	}

	lng, lngErr := strconv.ParseFloat(vars["lng"], 32)
	if lngErr != nil {
		ReturnErrorToClient(w, lngErr, "Invalid longitude value. Expecting a floating point number")
		return
	}

	tracelog.Trace("Lat Value", "main", "Lat is %f", lat)
	tracelog.Trace("Lng Value", "main", "Lng is %f", lng)

	postalCode, postaCodeErr := ReverseGeocodeToPostalCode(lat, lng)
	if postaCodeErr != nil {
		ReturnErrorToClient(w, postaCodeErr, "Error determining zip code from given coordinates")
		return
	}

	tracelog.Trace("Postal Code Value", "main", "Postal Code is %s", postalCode)
	var response = GeocodeResponse{postalCode}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(response); err != nil {
		tracelog.Error(err, "An error occurred while encoding json response", "NearbyHandler")
		panic(err)
	}
}
Beispiel #9
0
func DeleteLibrary(libId int64) bool {
	o := orm.NewOrm()
	if _, err := o.Delete(&Library{Id: libId}); err == nil {
		tracelog.Error(err, "Failed to delete lib", "model.DeleteLibrary")
		return false
	}
	return true
}
Beispiel #10
0
func DeleteBook(bookId int64) bool {
	o := orm.NewOrm()
	if _, err := o.Delete(&Book{Id: bookId}); err == nil {
		tracelog.Error(err, "Failed to query", "model.DeleteBook")
		return false
	}
	return true
}
// Prepare is called before any controller.
func (service *Service) Prepare() (err error) {
	service.MongoSession, err = mongo.CopyMonotonicSession(service.UserID)
	if err != nil {
		log.Error(err, service.UserID, "Service.Prepare")
		return err
	}

	return err
}
Beispiel #12
0
func GetBook(bookId int64) (*Book, error) {
	o := orm.NewOrm()
	book := Book{Id: bookId}
	err := o.Read(&book)
	if err != nil {
		tracelog.Error(err, "Failed to query", "model.GetBook")
	}
	return &book, err
}
Beispiel #13
0
func AddBookInLibrary(libraryId int64, bookId int64) bool {
	o := orm.NewOrm()
	_, err := o.Raw(`
		INSERT INTO book_library(book_id, library_id) VALUES(?, ?)`, bookId, libraryId).Exec()
	if err != nil {
		tracelog.Error(err, "Failed to query", "model.AddBookInLibrary")
		return false
	}
	return true
}
Beispiel #14
0
func (c *LibraryController) listBooksInLibrary() {
	libId, _ := strconv.ParseInt(c.Ctx.Input.Param(":libId"), 10, 64)
	books, err := model.GetBooksInLibrary(libId)

	if err == orm.ErrNoRows {
		tracelog.Error(err, "No result found", "MainController")
	}
	c.Data["json"] = &books
	c.ServeJson()
}
func main() {
	tracelog.Start(tracelog.LevelTrace)
	//tracelog.Start(tracelog.LevelInfo)

	var port = os.Getenv("PORT")

	if port == "" {
		tracelog.Error(nil, "The PORT environment variable has not been set.", "main")
		os.Exit(1)
	}

	var myGasFeedBaseUrl = os.Getenv("MY_GAS_FEED_BASE_URL")
	if myGasFeedBaseUrl == "" {
		tracelog.Error(nil, "The MY_GAS_FEED_BASE_URL environment variable has not been set.", "main")
	}
	SetMyGasFeedBaseUrl(myGasFeedBaseUrl)

	var myGasFeedApiKey = os.Getenv("MY_GAS_FEED_API_KEY")
	if myGasFeedApiKey == "" {
		tracelog.Error(nil, "The MY_GAS_FEED_API_KEY environment variable has not been set.", "main")
	}
	SetMyGasFeedApiKey(myGasFeedApiKey)

	tracelog.Info("Started", "main", "Gas Price Service is starting and listening on port %s", port)

	router := mux.NewRouter()
	for _, route := range routes {
		var handler http.Handler

		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)

		router.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(handler)
	}

	err := http.ListenAndServe(":"+port, router)
	if err != nil {
		tracelog.Error(err, "An error occurred while attempting to listen and serve", "main")
	}

	tracelog.Info("Stopped", "main", "Gas Price Service has been terminated")
	tracelog.Stop()
}
Beispiel #16
0
func (p *MgoCtx) login(db *mgo.Database) bool {
	if p.cfg.Pwd == "" {
		return true
	}
	if err := db.Login(p.cfg.User, p.cfg.Pwd); err != nil {
		log.Error(err, "Login", "mdb.Startup")
		return false
	}
	return true
}
Beispiel #17
0
func GetAllBooks() (*[]Book, error) {
	var rows []Book
	o := orm.NewOrm()
	_, err := o.Raw(`
		SELECT b.id, b.name, b.author 
		FROM book b`).QueryRows(&rows)
	if err != nil {
		tracelog.Error(err, "Failed to query", "model.GetAllBooks")
	}
	return &rows, err
}
Beispiel #18
0
func NewMgoCtx(cfg *MgoCfg) *MgoCtx {
	ctx := &MgoCtx{cfg: cfg}
	var err error
	if ctx.session, err = mgo.Dial(cfg.Server); err != nil {
		log.Error(err, "Dial", "mdb.Startup")
		panic(err)
	}
	ctx.session.SetMode(mgo.Strong, true)
	ctx.session.SetSafe(&mgo.Safe{W: 1})
	return ctx
}
Beispiel #19
0
//Libraries
func GetLibraries() (*[]Library, error) {
	var rows []Library
	o := orm.NewOrm()
	_, err := o.Raw(` 
		SELECT id, name 
		FROM library`).QueryRows(&rows)
	if err != nil {
		tracelog.Error(err, "Failed to GetLibraries", "model.GetLibraries")
	}
	return &rows, err
}
func publish(message string) {
	// Publish "hello world" on topic1.
	msgIDs, err := pubsub.Publish(getCtx(), "livefeed", &pubsub.Message{
		Data: []byte(message),
	})
	if err != nil {
		log.Println(err)
		tracelog.Error(err, `Error publishing to pubsub`, `publish`)
	} else {
		tracelog.Info(msgIDs[0], "publish", "Message stored in pubsub")
	}
}
func main() {
	// tracelog.Start(tracelog.LevelTrace)
	tracelog.Start(tracelog.LevelInfo)

	var port = os.Getenv("PORT")
	if port == "" {
		tracelog.Error(nil, "The PORT environment variable has not been set.", "main")
		os.Exit(1)
	}

	var mapsApiKey = os.Getenv("GOOGLE_MAPS_API_KEY")
	if mapsApiKey == "" {
		tracelog.Error(nil, "The GOOGLE_MAPS_API_KEY enviornment variable has not been set.", "main")
		os.Exit(2)
	}
	SetGoogleAPIKey(mapsApiKey)

	tracelog.Info("Started", "main", "Google Reverse Geocode Service is starting and listening on port %s", port)

	router := mux.NewRouter()
	for _, route := range routes {
		var handler http.Handler

		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)

		router.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(handler)
	}

	err := http.ListenAndServe(":"+port, router)
	if err != nil {
		tracelog.Error(err, "An error occurred while attempting to listen and serve.", "main")
		os.Exit(3)
	}

	tracelog.Info("Stopped", "main", "Google Reverse Geocode Service has been terminated")
	tracelog.Stop()
}
// Handles a transaction
func HandleTransaction(b []byte) {
	tracelog.Trace(TAG, "HandleTransaction", "Converting JSON to Transaction...")
	t := TransactionFromJSON(b)
	tracelog.Info(TAG, "HandleTransaction", t.String())

	msg := messages.TransactionMessage{Hash: t.Hash}

	jsonData, err := json.Marshal(msg)
	if err != nil {
		tracelog.Error(err, "Error trying to marshal", "HandleTransaction")
	}

	publish(string(jsonData))
}
Beispiel #23
0
func GetLibrary(libId int64) (*Library, error) {
	o := orm.NewOrm()
	lib := Library{Id: libId}
	err := o.Read(&lib)

	if err == orm.ErrNoRows {
		return nil, err
	} else if err == orm.ErrMissPK {
		tracelog.Error(err, "Failed to GetLibrary", "model.GetLibrary")
		return nil, err
	} else {
		return &lib, err
	}
}
Beispiel #24
0
func GetBooksInLibrary(libraryId int64) (*[]Book, error) {
	var rows []Book
	o := orm.NewOrm()
	_, err := o.Raw(`
		SELECT b.id, b.name, b.author 
		FROM book b 
		join book_library con on b.id = con.book_id 
		join library s on con.library_id = s.id
		WHERE s.id = ?`, libraryId).QueryRows(&rows)
	if err != nil {
		tracelog.Error(err, "Failed to query", "model.GetBooksInLibrary")
	}
	return &rows, err
}
Beispiel #25
0
func (c *BooksController) updateBook() {
	respByte, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		tracelog.Error(err, "Failed to read response data", "updateBook")
		c.Abort("500")
		return
	}
	res := model.UpdateBook(respByte)
	if !res {
		c.Abort("500")
	}
	c.Data["json"] = &res
	c.ServeJson()
}
// Prepare is called before controllers are called.
func Prepare() *services.Service {
	var service services.Service

	// TODO: Add Test User To Environment
	service.UserID = "testing"

	err := service.Prepare()
	if err != nil {
		log.Error(err, service.UserID, "Prepare")
		return nil
	}

	log.Trace(service.UserID, "Before", "UserID[%s]", service.UserID)
	return &service
}
func NearbyHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	var placeType = vars["type"]
	// TODO: may want to validate type

	lat, latErr := strconv.ParseFloat(vars["lat"], 32)
	if latErr != nil {
		ReturnErrorToClient(w, latErr, "Invalid latitude value. Expecting a floating point number")
		return
	}

	lng, lngErr := strconv.ParseFloat(vars["lng"], 32)
	if lngErr != nil {
		ReturnErrorToClient(w, lngErr, "Invalid longitude value. Expecting a floating point number")
		return
	}

	tracelog.Trace("Type Value", "main", "Type is %s", placeType)
	tracelog.Trace("Lat Value", "main", "Lat is %f", lat)
	tracelog.Trace("Lng Value", "main", "Lng is %f", lng)

	response, nearbyErr := NearbySearch(placeType, lat, lng)
	if nearbyErr != nil {
		ReturnErrorToClient(w, nearbyErr, "Nearby Search returned an error")
		return
	}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(response); err != nil {
		tracelog.Error(err, "An error occurred while encoding json response", "NearbyHandler")
		panic(err)
	}
}