本文整理汇总了Golang中github.com/dancannon/gorethink.Table函数的典型用法代码示例。如果您正苦于以下问题:Golang Table函数的具体用法?Golang Table怎么用?Golang Table使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Table函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: deleteHandler
func deleteHandler(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id := vars["id"]
if id == "" {
http.NotFound(w, req)
return
}
// Check that the item exists
res, err := r.Table("items").Get(id).Run(session)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res.IsNil() {
http.NotFound(w, req)
return
}
// Delete the item
_, err = r.Table("items").Get(id).Delete().RunWrite(session)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, req, "/", http.StatusFound)
}
示例2: UserUtils
func UserUtils(res http.ResponseWriter, req *http.Request) {
if req.Method == "POST" {
name := req.FormValue("name")
user := &User{name}
_, err := r.Table("users").Insert(user).RunWrite(session)
if err != nil {
fmt.Print("Error: %s", err)
} else {
io.WriteString(res, "Insertado con exito")
}
}
if req.Method == "DELETE" {
id := req.FormValue("id")
_, err := r.Table("users").Get(id).Delete().RunWrite(session)
if err != nil {
fmt.Print("Error: %s", err)
} else {
io.WriteString(res, "Eliminado con exito")
}
}
if req.Method == "PUT" {
id := req.FormValue("id")
name := req.FormValue("name")
user := &User{name}
_, err := r.Table("users").Get(id).Update(user).RunWrite(session)
if err != nil {
fmt.Print("Error: %s", err)
} else {
io.WriteString(res, "Actualizado con exito")
}
}
}
示例3: toggleHandler
func toggleHandler(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id := vars["id"]
if id == "" {
http.NotFound(w, req)
return
}
// Check that the item exists
res, err := r.Table("items").Get(id).Run(session)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res.IsNil() {
http.NotFound(w, req)
return
}
// Toggle the item
_, err = r.Table("items").Get(id).Update(map[string]interface{}{"Status": r.Branch(
r.Row.Field("Status").Eq("active"),
"complete",
"active",
)}).RunWrite(session)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, req, "/", http.StatusFound)
}
示例4: ToggleNode
func (s *HTTPServer) ToggleNode(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id := vars["id"]
if id == "" {
http.NotFound(w, req)
return
}
// Check that the item exists
res, err := r.Table(tableIpxe).Get(id).RunRow(session)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res.IsNil() {
http.NotFound(w, req)
return
}
_, err = r.Table(tableIpxe).Get(id).Update(map[string]interface{}{"Status": r.Branch(
r.Row.Field("Status").Eq("AVAILABLE"),
"UNAVAILABLE",
"AVAILABLE",
)}).RunWrite(session)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, req, "/", http.StatusFound)
}
示例5: RemoveEngine
func (m *Manager) RemoveEngine(id string) error {
var engine *shipyard.Engine
res, err := r.Table(tblNameConfig).Filter(map[string]string{"id": id}).Run(m.session)
if err != nil {
return err
}
if err := res.One(&engine); err != nil {
if err == r.ErrEmptyResult {
return nil
}
return err
}
evt := &shipyard.Event{
Type: "remove-engine",
Message: fmt.Sprintf("addr=%s", engine.Engine.Addr),
Time: time.Now(),
Engine: engine.Engine,
Tags: []string{"cluster"},
}
if err := m.SaveEvent(evt); err != nil {
return err
}
if _, err := r.Table(tblNameConfig).Get(id).Delete().RunWrite(m.session); err != nil {
return err
}
m.init()
return nil
}
示例6: createHub
func createHub(user sessionauth.User, newHub hub, rend render.Render, req *http.Request) {
var hubInDB hub
query := r.Table("hub").Filter(r.Row.Field("name").Eq(newHub.HubName))
row, err := query.RunRow(dbSession)
if err == nil && !row.IsNil() {
// Register, error case.
if err := row.Scan(&hubInDB); err != nil {
fmt.Println("Error reading DB")
} else {
fmt.Println("User already exists. Redirecting to login.")
}
rend.Redirect(sessionauth.RedirectUrl)
return
} else { // User doesn't exist, continue with registration.
if row.IsNil() {
fmt.Println("User doesn't exist. Registering...")
} else {
fmt.Println(err)
}
}
r.Table("hub").Insert(newHub).RunWrite(dbSession)
fmt.Println("New hub done. Try to con")
rend.Redirect(sessionauth.RedirectUrl)
}
示例7: init
func init() {
h = &hubManager{
HubMap: make(map[string]*hub),
EdgeMap: &Edges{},
newHub: make(chan hubConnMsg, 256),
addEdge: make(chan hubConnMsg, 2048),
remEdge: make(chan hubConnMsg, 2048),
bCastToHub: make(chan hubConnMsg, 2048),
}
var err error
h.DefaultHub, err = newHub("default", nil)
if err != nil {
fmt.Println("Default insert error, still running hub.", err)
}
// create index
_, err = r.Table("hub").IndexCreate("name").Run(dbSession)
fmt.Println("create index name error: ", err)
_, err = r.Table("user").IndexCreate("email").Run(dbSession)
fmt.Println("create index user email error: ", err)
go h.run()
}
示例8: init
func init() {
flag.Parse()
err := gcfg.ReadFileInto(&cfg, *configFile)
if err != nil {
log.Fatal(err)
}
session, err = r.Connect(r.ConnectOpts{
Address: cfg.Database.Host + ":" + cfg.Database.Port, //localhost:28015
Database: cfg.Database.DB, //DB: cats
})
if err != nil {
log.Fatal("Could not connect")
}
res, err := r.DBCreate(cfg.Database.DB).RunWrite(session)
if err != nil {
log.Println(err.Error())
}
fmt.Printf("%d DB created\n", res.DBsCreated)
r.DB(cfg.Database.DB).TableCreate("instacat").Run(session)
log.Println("Create table instacat.")
r.Table("instacat").IndexCreate("time").Run(session)
log.Println("Create index time.")
r.Table("instacat").IndexCreate("place", r.IndexCreateOpts{Geo: true}).Run(session)
log.Println("Create index place.")
}
示例9: SaveAccount
func (m *Manager) SaveAccount(account *shipyard.Account) error {
pass := account.Password
hash, err := m.authenticator.Hash(pass)
if err != nil {
return err
}
// check if exists; if so, update
acct, err := m.Account(account.Username)
if err != nil && err != ErrAccountDoesNotExist {
return err
}
account.Password = hash
if acct != nil {
if _, err := r.Table(tblNameAccounts).Filter(map[string]string{"username": account.Username}).Update(map[string]string{"password": hash}).RunWrite(m.session); err != nil {
return err
}
return nil
}
if _, err := r.Table(tblNameAccounts).Insert(account).RunWrite(m.session); err != nil {
return err
}
evt := &shipyard.Event{
Type: "add-account",
Time: time.Now(),
Message: fmt.Sprintf("username=%s", account.Username),
Tags: []string{"cluster", "security"},
}
if err := m.SaveEvent(evt); err != nil {
return err
}
return nil
}
示例10: getRemoteObject
func getRemoteObject(url string) (Object, error) {
rows, err := gorethink.Table("objects").GetAllByIndex("url", url).Run(session)
var row Object
err = rows.One(&row)
if err != nil && err != gorethink.ErrEmptyResult {
return Object{}, err
}
if err == gorethink.ErrEmptyResult {
res, err := http.Get(url)
if err != nil {
return Object{}, err
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
return Object{}, err
}
result, err := gorethink.Table("objects").Insert(Object{URL: url, Content: content}).RunWrite(session)
if err != nil {
return Object{}, err
}
return Object{ID: result.GeneratedKeys[0], URL: url, Content: content}, nil
}
return row, nil
}
示例11: pushIndex
func pushIndex(session *gorethink.Session) {
i := 0
fmt.Println("Pushing title")
for i < len(titles) {
var chunk []*Title
if i+100 < len(titles) {
chunk = titles[i : i+100]
} else {
chunk = titles[i:len(titles)]
}
gorethink.Table("titles").Insert(chunk, gorethink.InsertOpts{Durability: "soft", Upsert: true}).RunWrite(session)
fmt.Println("Title %d / %d\n", i, len(titles))
i += 100
}
fmt.Println("Pushing index")
idxChunk := []*Index{}
i = 0
for _, idx := range idxes {
i++
if len(idxChunk) < 100 {
idxChunk = append(idxChunk, idx)
continue
}
gorethink.Table("indexes").Insert(idxChunk, gorethink.InsertOpts{Durability: "soft", Upsert: true}).RunWrite(session)
fmt.Println("Index %d / %d\n", i, len(idxes))
idxChunk = []*Index{}
}
}
示例12: PutBuild
func (rd *rethinkDriver) PutBuild(build *datastore.Build) (string, error) {
result, err := r.Table("builds").Insert(
r.Table("builds").Filter(
r.And(
r.Row.Field("job_id").Eq(build.JobId),
r.Row.Field("number").Eq(build.Number),
),
).CoerceTo("array").Do(func(docs r.Term) interface{} {
return r.Branch(
r.Or(docs.IsEmpty(), docs.Field("id").Contains(build.Id)),
build,
r.Error("Build with job_id and number exists"),
)
}),
r.InsertOpts{Conflict: "replace"},
).RunWrite(rd.session)
if err != nil {
return "", err
}
if len(result.GeneratedKeys) > 0 {
return result.GeneratedKeys[0], nil
} else {
return build.Id, nil
}
}
示例13: UpdateTripPlaces
//UpdateTripPlaces update trip places
func (t *Trips) UpdateTripPlaces(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
res, err := rethink.Table(tableName).Get(id).Run(t.Conn)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res.IsNil() {
rest.NotFound(w, r)
return
}
var trip *Trip
res.One(&trip)
tripPlaces := []TripPlace{}
err = r.DecodeJsonPayload(&tripPlaces)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
trip.Updated = time.Now()
trip.Places = tripPlaces
trip.TotalPlaces = len(tripPlaces)
_, err = rethink.Table(tableName).Get(id).Update(trip).RunWrite(t.Conn)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&trip)
}
示例14: buy
func buy(w http.ResponseWriter, q *http.Request) {
ctx, err := NewContext(q)
if err != nil {
log.Println(err)
}
if q.Method == "POST" {
//find last code(chek if it) of order +1 add to db
t := time.Now()
order := ctx.Session.Values["Order"].(*Order)
a := false
for a == false {
orderId := getorderId(t.Format("2006-01-02"), order.Customer.Email, randStr(4, "alphanum"))
res, err := r.Table("orders").Filter(map[string]interface{}{"OrderNumber": orderId}).Run(ctx.Db)
if err != nil {
log.Println(err)
}
if res.IsNil() == true {
p := findproductCart{
CartArray: order.CartOrderd,
}
_, total := p.total()
P, _, _, _ := statuses()
//P, PfS, S, D := statuses()
order.OrderNumber = orderId
order.Status = P
order.Date = t.Format("2006-01-02 15:04")
order.Total = FloatToString(total)
_, err = r.Table("orders").Insert(order).RunWrite(ctx.Db)
if err != nil {
log.Println(err)
}
ctx.Session.Values["Order"] = nil
ctx.Session.Save(q, w)
a = true
} else {
a = false
}
}
} else {
order := ctx.Session.Values["Order"].(*Order)
newmap := map[string]interface{}{"Shippingadress": order.ShippingAdress, "Billingadress": order.BillingAdress, "Paymethod": order.PaymentMethod, "shippingOpt": order.Shipping.ShippingMethod, "Product": order.CartOrderd}
render(w, "buy", newmap)
}
}
示例15: SaveAuthorization
func (s *Rethinkdb) SaveAuthorization(auth *dialogue.Authorization) error {
// delete exiting
rdb.Table(AUTH_TABLE).Filter(map[string]string{"username": auth.Username}).Delete().Run(s.session)
// add auth
if _, err := rdb.Table(AUTH_TABLE).Insert(auth).Run(s.session); err != nil {
return err
}
return nil
}