func GetRegionHandler(w http.ResponseWriter, r *http.Request) { regionName := mux.Vars(r)["name"] db, err := sql.Open("postgres", os.Getenv("DATABASE_URL")) if err != nil { w.WriteHeader(500) errResp := NewResponse(nil, err.Error()) errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } var region string err = db.QueryRow(`SELECT geo FROM regions WHERE name = $1`, regionName). Scan(®ion) if err != nil && err.Error() == "sql: no rows in result set" { w.WriteHeader(404) errResp := NewResponse(nil, "region does not exist") errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } rr := Response{ Error: "", Results: region, } var respRaw []byte respRaw, err = json.Marshal(rr) if err != nil { w.WriteHeader(500) errResp := NewResponse(nil, err.Error()) errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } w.Write(respRaw) }
func SaveRegionHandler(w http.ResponseWriter, r *http.Request) { regionName := mux.Vars(r)["name"] reqRaw, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(400) errResp := NewResponse(nil, err.Error()) errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } r.Body.Close() var rb RequestBody err = json.Unmarshal(reqRaw, &rb) if err != nil { w.WriteHeader(400) errResp := NewResponse(nil, err.Error()) errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } db, err := sql.Open("postgres", os.Getenv("DATABASE_URL")) if err != nil { w.WriteHeader(500) errResp := NewResponse(nil, err.Error()) errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } now := time.Now().Format(time.RFC3339) name := strings.Replace(regionName, " ", "_", -1) _, err = db.Exec(`INSERT INTO regions ("name", "collection", "geo", "added_date") VALUES ($1, 'custom', $2, $3);`, name, rb.Region, now) if err != nil { w.WriteHeader(400) errResp := NewResponse(nil, "region name already exists") errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } rr := Response{ Error: "", Results: "/#user/" + name, } respRaw, err := json.Marshal(rr) if err != nil { w.WriteHeader(500) errResp := NewResponse(nil, err.Error()) errRespRaw, _ := json.Marshal(errResp) w.Write(errRespRaw) return } w.Write(respRaw) return }