func main() { // To access a RethinkDB database, you connect to it with the Connect function session, err := r.Connect("localhost:28015", "company_info") if err != nil { fmt.Println("error connecting:", err) return } var response []Employee // Using .All(), we can read the entire response into a slice, without iteration err = r.Table("employees").Run(session).All(&response) if err != nil { fmt.Println("err:", err) } else { fmt.Println("response:", response) } // If we want to iterate over each result individually, we can use the rows // object as an iterator rows := r.Table("employees").Run(session) for rows.Next() { var row Employee if err = rows.Scan(&row); err != nil { fmt.Println("err:", err) break } fmt.Println("row:", row) } if err = rows.Err(); err != nil { fmt.Println("err:", err) } }
func RegisterUser(user, password string, context *ServerContext) (err error) { request := r.Table("login").Filter(r.Row.Attr("Username").Eq(user)) var result []LoginDBEntry if err = context.DB.MakeRequest(request).All(&result); err != nil { return } if len(result) == 1 { err = errors.New("Duplicate user") return } pepper := []byte(pepperStr) pass := []byte(password) crypt := hmaccrypt.New(sha512.New, pepper) var digest []byte if digest, err = crypt.Bcrypt(pass, 10); err != nil { return } digestStr := string(digest) row := LoginDBEntry{user, digestStr} request = r.Table("login").Insert(row) err = context.DB.MakeRequest(request).Err() return }
func todoCreateHandler(w http.ResponseWriter, r *http.Request) { var todo Todo var response rethink.WriteResponse todoBody, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Println("Error reading request body:", err) } err = json.Unmarshal(todoBody, &todo) if err != nil { fmt.Println("Error unmarshalling request body:", err) } err = rethink.Table(TODO_TABLE).Insert(todo).Run(session).One(&response) if err != nil { fmt.Println("Error inserting record:", err) } responseBody := map[string]string{} responseBody["id"] = response.GeneratedKeys[0] responseBodyText, err := json.Marshal(responseBody) if err != nil { fmt.Println("Unable to marshal response:", err) } fmt.Fprintf(w, "%s", responseBodyText) }
// This will convert a URL into a short url func ShortenHandler(w http.ResponseWriter, request *http.Request, session *r.Session) { body, err := ioutil.ReadAll(request.Body) if err != nil { http.Error(w, fmt.Sprintf("Could not parse POST body: %v", err), http.StatusInternalServerError) } var postRequest POSTRequest err = json.Unmarshal(body, &postRequest) if err != nil { http.Error(w, fmt.Sprintf("Could not decode JSON: %v", err), http.StatusPreconditionFailed) } url := postRequest.URL var response r.WriteResponse row := r.Map{"url": url} err = r.Table("url_mapping").Insert(row).Run(session).One(&response) if err != nil { log.Print(err) http.Error(w, "Could not save URL", http.StatusInternalServerError) } id := response.GeneratedKeys[0] fmt.Fprintf(w, "http://%s/%s", request.Host, id) }
func (c AccountsController) CreateAccount(account models.Account, render render.Render, session *rethinkgo.Session) { log.Println("account", account) err := rethinkgo.Table("accounts").Insert(account).Run(session).Err() if err != nil { panic(err) } c.GetAccounts(render, session) }
func (c AccountsController) GetAccount(params martini.Params, render render.Render, session *rethinkgo.Session) { var account *models.Account err := rethinkgo.Table("accounts").Get(params["id"]).Run(session).One(&account) if err != nil { panic(err) } render.JSON(200, account) }
func (c AccountsController) GetAccounts(render render.Render, session *rethinkgo.Session) { var accounts []*models.Account err := rethinkgo.Table("accounts").Run(session).All(&accounts) if err != nil { panic(err) } render.JSON(200, accounts) }
func handleIndex(res http.ResponseWriter, req *http.Request) { session := sessionArray[0] var response []Bookmark err := r.Table("bookmarks").Run(session).All(&response) if err != nil { log.Fatal(err) } data, _ := json.Marshal(response) res.Header().Set("Content-Type", "application/json") res.Write(data) }
func (self User) All() []User { log.Println("User.All") session := database.getSession() var users []User err := rethinkgo.Table("users").Run(session).All(&users) if err != nil { log.Println("[ERROR] User.All: ", err) panic(err) } return users }
func (self User) FindById(id string) User { log.Println("User.FindById") session := database.getSession() var user User err := rethinkgo.Table("users").Get(id).Run(session).One(&user) if err != nil { log.Println("[ERROR] User.All: ", err) panic(err) } return user }
func insertBookmark(res http.ResponseWriter, req *http.Request) { session := sessionArray[0] b := new(Bookmark) json.NewDecoder(req.Body).Decode(b) var response r.WriteResponse err := r.Table("bookmarks").Insert(b).Run(session).One(&response) if err != nil { log.Fatal(err) return } data, _ := json.Marshal("{'bookmark':'saved'}") res.Header().Set("Content-Type", "application/json; charset=utf-8") res.Write(data) }
// This will convert a short URL into the full website func EmbiggenHandler(w http.ResponseWriter, request *http.Request, session *r.Session) { vars := mux.Vars(request) key := vars["key"] //id := utils.Decode(key) var result map[string]interface{} err := r.Table("url_mapping").Get(key, "id").Run(session).One(&result) if err != nil || len(result) == 0 { log.Print(err) http.NotFound(w, request) } url := result["url"] fmt.Fprintf(w, "%s", url) }
func VerifyPassword(user, password string, context *ServerContext) (valid bool, err error) { request := r.Table("login").Filter(r.Row.Attr("Username").Eq(user)) var result []LoginDBEntry err = context.DB.MakeRequest(request).All(&result) digestStr := result[0].Password digest := []byte(digestStr) pass := []byte(password) pepper := []byte(pepperStr) crypt := hmaccrypt.New(sha512.New, pepper) if err = crypt.BcryptCompare(digest, pass); err == nil { valid = true } else { valid = false } return }
func (self User) Create(params map[string]string) User { // Setup session session := database.getSession() // Setup table table := rethinkgo.Table("users") errors := make(map[string]string) user := User{Username: params["username"], FirstName: params["first_name"], LastName: params["last_name"], Email: params["email"], Handle: params["handle"]} if params["password"] != params["password_confirmation"] { errors["password"] = "******" user.Errors = errors } else { userMap := rethinkgo.Map{ "username": params["username"], "password_hash": passwordHash(params["password"]), "first_name": params["first_name"], "last_name": params["last_name"], "email": params["email"], "handle": params["handle"], "created_at": time.Now()} // insert the reading var response rethinkgo.WriteResponse err := table.Insert(userMap).Run(session).One(&response) if err != nil { log.Println("[ERROR] User.Create: ", err) errors["unknown"] = err.Error() user.Errors = errors } } return user }
func (todo *Todo) Delete() (rethink.WriteResponse, error) { var response rethink.WriteResponse err := rethink.Table(TODO_TABLE).Get(todo.Id).Delete().Run(session).One(&response) return response, err }
func (todo *Todo) Update() (response rethink.WriteResponse, err error) { err = rethink.Table(TODO_TABLE).Get(todo.Id).Update(todo).Run(session).One(&response) return }
func getTodo(id string) (todo Todo, err error) { err = rethink.Table(TODO_TABLE).Get(id).Run(session).One(&todo) return }
func getTodos() (todos []Todo, err error) { err = rethink.Table(TODO_TABLE).Run(session).All(&todos) return }