func handleDatabase(w http.ResponseWriter, db nosql.Database, method string) { switch { case method == "GET": exists, err := db.Exists(ctx) if err != nil { http.Error(w, "error in db.Exists()", 500) return } if !exists { http.Error(w, "db doesn't exist", 404) return } tables, err := db.ListTables(ctx) if err != nil { http.Error(w, "error in db.ListTables()", 500) return } urls := make([]string, len(tables)) for i, tableName := range tables { urls[i] = fmt.Sprintf("//%s/%s", db.Name(), tableName) } jsondat, err := json.Marshal(urls) if err != nil { http.Error(w, "error generating JSON", 500) return } w.Header().Add("Content-type", "Application/json") w.Write(jsondat) case method == "POST": exists, err := db.Exists(ctx) if err != nil { http.Error(w, "error in db.Exists()", 500) return } if exists { http.Error(w, "database already exists", 409) return } if err := db.Create(ctx, nil); err != nil { http.Error(w, "error creating database", 500) return } default: http.Error(w, "unsupported method for database", 400) return } }
func handleTable(w http.ResponseWriter, db nosql.Database, t nosql.Table, method string) { switch { case method == "GET": exists, err := t.Exists(ctx) if err != nil { http.Error(w, "error in table.Exists()", 500) return } if !exists { http.Error(w, "table doesn't exist", 404) return } rnge := nosql.Prefix("") stream := t.Scan(ctx, rnge) urls := []string{} for stream.Advance() { url := fmt.Sprintf("//%s/%s/%s", db.Name(), t.Name(), stream.Key()) urls = append(urls, url) } jsondat, err := json.Marshal(urls) if err != nil { http.Error(w, "error generating JSON", 500) return } w.Header().Add("Content-type", "Application/json") w.Write(jsondat) case method == "POST": exists, err := t.Exists(ctx) if err != nil { http.Error(w, "error in table.Exists()", 500) return } if exists { http.Error(w, "table already exists", 409) return } if err := t.Create(ctx, nil); err != nil { http.Error(w, "error creating table", 500) return } default: http.Error(w, "unsupported method for database", 400) return } }
func handleRest(w http.ResponseWriter, db nosql.Database, remainder string, r *http.Request) { strs := strings.SplitN(remainder, "/", 2) method := r.Method exists, err := db.Exists(ctx) if err != nil { http.Error(w, "error in db.Exists()", 500) return } if !exists { http.Error(w, "database doesn't exist", 404) return } tableName := strs[0] t := db.Table(tableName) if len(strs) == 1 { handleTable(w, db, t, method) return } // TODO(bprosnitz) Is there a race between table Exists and Create? exists, err = t.Exists(ctx) if err != nil { http.Error(w, "error in table.Exists()", 500) return } if !exists { http.Error(w, "table doesn't exist", 404) return } key := strs[1] body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "error reading message body", 500) return } fmt.Printf("DB: %s Table: %s Key: %s method: %s value: %q\n", db.Name(), tableName, key, method, body) row := t.Row(key) handleRow(w, row, key, string(body), method) }