package main import ( "encoding/json" "log" "net/http" "strings" ) type Restaurant struct { RestaurantId int64 Name string } type RestaurantList struct { Restaurants *[]*Restaurant `json:"restaurants"` } func (r *Restaurant) Write(w http.ResponseWriter) error { enc := json.NewEncoder(w) return enc.Encode(r) } func (r *Restaurant) Read(json_str string) error { dec := json.NewDecoder(strings.NewReader(json_str)) return dec.Decode(r) } func (rl *RestaurantList) Write(w http.ResponseWriter) error { enc := json.NewEncoder(w) return enc.Encode(rl) } type RestaurantExistsError struct{} func (aeu RestaurantExistsError) Error() string { return "Restaurant exists" } func GetRestaurants() (*[]*Restaurant, error) { var restaurants []*Restaurant _, err := DB.Select(&restaurants, "SELECT * from restaurants") if err != nil { return nil, err } return &restaurants, nil } func InsertRestaurant(r *Restaurant) error { transaction, err := DB.Begin() if err != nil { return err } existing, err := transaction.SelectInt("SELECT count(*) from users where Name=?", r.Name) if err != nil { transaction.Rollback() return err } if existing > 0 { transaction.Rollback() return RestaurantExistsError{} } err = transaction.Insert(r) if err != nil { transaction.Rollback() return err } err = transaction.Commit() if err != nil { transaction.Rollback() return err } return nil } func RestaurantHandler(w http.ResponseWriter, r *http.Request) { _, err := GetUserFromSession(r) if err != nil { WriteError(w, 1 /*Not Signed In*/) return } if r.Method == "POST" { restaurant_json := r.PostFormValue("restaurant") if restaurant_json == "" { WriteError(w, 3 /*Invalid Request*/) return } var restaurant Restaurant err := restaurant.Read(restaurant_json) if err != nil { WriteError(w, 3 /*Invalid Request*/) return } restaurant.RestaurantId = -1 err = InsertRestaurant(&restaurant) if err != nil { if _, ok := err.(RestaurantExistsError); ok { WriteError(w, 6 /*Restaurant Exists*/) } else { WriteError(w, 999 /*Internal Error*/) log.Print(err) } return } w.WriteHeader(201 /*Created*/) err = restaurant.Write(w) if err != nil { WriteError(w, 999 /*Internal Error*/) log.Print(err) return } } else if r.Method == "GET" { var rl RestaurantList restaurants, err := GetRestaurants() if err != nil { WriteError(w, 999 /*Internal Error*/) log.Print(err) return } rl.Restaurants = restaurants err = (&rl).Write(w) if err != nil { WriteError(w, 999 /*Internal Error*/) log.Print(err) return } } else { /* No PUT or DELETE */ WriteError(w, 3 /*Invalid Request*/) return } }