func addTagToFact(c appengine.Context, factKey *datastore.Key, tag string) { q := datastore.NewQuery("Tag").Filter("Name =", tag) cnt, _ := q.Count(c) var existingTag Tag var existingTagKey *datastore.Key if cnt > 0 { // retrieve for t := q.Run(c); ; { existingTagKey, _ = t.Next(&existingTag) break // only need one } } else { // create a new one var t = Tag{Name: tag} existingTagKey, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "Tag", nil), &t) } qft := datastore.NewQuery("FactTag"). Filter("Fact = ", factKey). Filter("Tag = ", existingTagKey) cnt2, _ := qft.Count(c) if cnt2 == 0 { // create a new one var ft = FactTag{Fact: factKey, Tag: existingTagKey} _, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "FactTag", nil), &ft) } }
func createNewGame(c appengine.Context, userId string, players []string) (Game, error) { g := Game{ UserId: userId, Started: time.Now(), Players: players, } err := datastore.RunInTransaction(c, func(c appengine.Context) error { key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "game", nil), &g) if err != nil { return err } // For now just add all players into the queue. for _, p := range players { qp := QueuePlayer{ UserId: p, Timestamp: time.Now(), } _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "queueplayer", key), &qp) if err != nil { return err } } g.Id = key.Encode() return nil }, nil) return g, err }
func (handler *userHandler) Post(r *fhttp.JsonRequest) fhttp.Response { user := new(models.User) err := r.Extract(user) if err != nil { return fhttp.UserError("invalid json") } if user.Nickname == "" { return fhttp.UserError("nickname cannot be empty") } context := appengine.NewContext((*http.Request)(r)) userKey, err := datastore.Put(context, datastore.NewIncompleteKey(context, "User", nil), user) if err != nil { return fhttp.ServerError(err.String()) } auth := models.NewAuth(userKey) _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Auth", nil), auth) if err != nil { return fhttp.ServerError(err.String()) } return fhttp.JsonResponse{ &postResponse{ fmt.Sprintf("%x", auth.Public), }, } }
func save(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } c := appengine.NewContext(r) u := user.Current(c) tags := strings.Split(r.FormValue("tags"), ",") p := datatypes.Post{ Author: u.String(), Title: r.FormValue("title"), Text: r.FormValue("blogcontent"), GoDate: time.Now(), ID: -1, Tags: tags, } key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "posts", nil), &p) if err != nil { log.Fatal(err) } for i := range tags { _, err := datastore.Put(c, datastore.NewIncompleteKey(c, tags[i], nil), &p) if err != nil { log.Fatal(err) } } time.Sleep(500 * time.Millisecond) http.Redirect(w, r, "/posts/"+strconv.FormatInt(key.IntID(), 10), http.StatusFound) }
func addTestData(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) e := DiaryEntry{ Author: "Julian", Content: []byte(`Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`), Date: (time.Now()).Add(time.Hour * 24), CreationTime: time.Now(), } _, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "DiaryEntry", nil), &e) e = DiaryEntry{ Author: "Julian", Content: []byte("It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)."), Date: time.Now(), CreationTime: time.Now(), } _, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "DiaryEntry", nil), &e) w.Header().Set("Status", "302") w.Header().Set("Location", "/") }
func SavePost(context appengine.Context, title string, content appengine.BlobKey, tags []string, postdate time.Time) (*datastore.Key, error) { // transaction temppostkey := datastore.NewIncompleteKey(context, "post", nil) p1 := Post{ Title: title, Content: content, Postdate: postdate, StickyUrl: conv_title_to_url(title), Tags: tags, } postkey, err := datastore.Put(context, temppostkey, &p1) if err != nil { return nil, err } tagkey := datastore.NewIncompleteKey(context, "tagindices", postkey) t1 := TagIndex{ Tags: tags, Postdate: postdate, } _, err = datastore.Put(context, tagkey, &t1) if err != nil { return nil, err } tagcounts, err := CalculateTagCounts(context) if err != nil { return nil, err } var name []string var count []int for k, v := range tagcounts { name = append(name, k) count = append(count, v) } taggggkey := datastore.NewKey(context, "tagcounts", "", 1, nil) t2 := TagCounts{ Name: name, Count: count, } _, err = datastore.Put(context, taggggkey, &t2) if err != nil { return nil, err } // end transaction return postkey, nil }
func initStock(c appengine.Context, w http.ResponseWriter, stocks []Stock) { if len(stocks) == 0 { googleStock := &Stock{Empresa: "Google", Puntos: 1000} amazonStock := &Stock{Empresa: "Amazon", Puntos: 900} keyGoogle := datastore.NewIncompleteKey(c, "Stock", nil) keyAmazon := datastore.NewIncompleteKey(c, "Stock", nil) if _, err := datastore.Put(c, keyGoogle, googleStock); err != nil { c.Errorf("Error al inicializar los valores de google. %v", err) } if _, err := datastore.Put(c, keyAmazon, amazonStock); err != nil { c.Errorf("Error al inicializar los valores de amazon. %v", err) } c.Debugf("datastore inicializado con los valores de prueba inciales") } }
func signupPost(w http.ResponseWriter, r *http.Request) { responseType, client, err := params(r) if err != nil { err.WriteTo(w) return } email, password := r.FormValue("email"), r.FormValue("password") emailRegexp := regexp.MustCompile(`^[a-z0-9._%\-+]+@[a-z0-9.\-]+\.[a-z]+$`) msgs := make([]string, 0, 5) if !emailRegexp.MatchString(email) { msgs = append(msgs, "Invalid email address") } if len(password) < 6 { msgs = append(msgs, "Password is too short") } // Also check if email already exists user := model.NewUser(email) context := appengine.NewContext(r) countExists, e := datastore.NewQuery("User").Filter("EmailHash =", user.EmailHash).Count(context) if e != nil { context.Errorf("%v", e) http.Error(w, e.String(), http.StatusInternalServerError) return } if countExists > 0 { msgs = append(msgs, "Email already exists") } if msgsLen := len(msgs); msgsLen > 0 { http.RedirectHandler("/oauth2/signup?response_type="+url.QueryEscape(responseType)+"&client_id="+ url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape(strings.Join(msgs, "|")), 303).ServeHTTP(w, r) } else { userKey, err := datastore.Put(context, datastore.NewIncompleteKey(context, "User", nil), user) if err != nil { context.Errorf("Error saving: %v", err) w.Write([]byte("Error saving: " + err.String())) return } auth := model.NewPasswordAuth(userKey, password) if _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Authentication", nil), auth); err != nil { context.Errorf("Error saving: %v", err) w.Write([]byte("Error saving: " + err.String())) return } key := newCodeKey(userKey.StringID(), client.Id, context) http.RedirectHandler(client.redirectUrl(key), 303).ServeHTTP(w, r) } }
func (o *Purchaser) key(c appengine.Context) *datastore.Key { if o.Id == 0 { o.Created = time.Now() return datastore.NewIncompleteKey(c, "Purchaser", defaultPurchaserList(c)) } return datastore.NewKey(c, "Purchaser", "", int64(o.Id), defaultPurchaserList(c)) }
// req: POST /items/ {"Title": "Buy bread"} // resp: 201 func NewItem(w http.ResponseWriter, r *http.Request) error { req := struct{ Title string }{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return badRequest{err} } if req.Title == "" { return fmt.Errorf("Empty title!") } newItem := newDefaultItem() newItem.Title = req.Title c := appengine.NewContext(r) itemKey, e := datastore.Put(c, datastore.NewIncompleteKey(c, "Item", nil), newItem) if e != nil { return e } newItem.ID = itemKey.IntID() _, e = datastore.Put(c, itemKey, newItem) // log.Println("newItem.ID -> ", newItem.ID) if e != nil { return e } newUrl := r.URL.Path + strconv.FormatInt(newItem.ID, 10) w.Header().Set("Location", newUrl) w.WriteHeader(http.StatusCreated) return nil }
// createTask parses a task from the request body in JSON format and adds it to // the list with the id given in the url. Finally it encodes the created task // with the generated id into the http response. func createTask(w io.Writer, r *http.Request) error { c := appengine.NewContext(r) // Decode the list id in the URL and check the current user is the creator. listKey, creator, err := decode(mux.Vars(r)["list"]) if err != nil { return err } if creator != user.Current(c).Email { return appErrorf(http.StatusForbidden, "only %v can do this", creator) } // Decode the task from the request body. task := Task{} err = json.NewDecoder(r.Body).Decode(&task) if err != nil { return appErrorf(http.StatusBadRequest, "decode task: %v", err) } if task.Text == "" { return appErrorf(http.StatusBadRequest, "missing task text") } // Set the creation time in the task and put it in the datastore. task.Time = time.Now().Unix() key := datastore.NewIncompleteKey(c, taskKind, listKey) key, err = datastore.Put(c, key, &task) if err != nil { return fmt.Errorf("add task: %v", err) } // Add the encoded key before encoding the task to JSON. task.ID = key.IntID() return json.NewEncoder(w).Encode(task) }
func handleNewSong(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) song := parseSongForm(w, r) _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Song", nil), &song) handleErr(err, w) }
func (a *AboutUs) key(ctx appengine.Context) *datastore.Key { if a.ID == 0 { a.DateAdded = time.Now() return datastore.NewIncompleteKey(ctx, "AboutUs", defaultAboutUs(ctx)) } return datastore.NewKey(ctx, "AboutUs", "", a.ID, defaultAboutUs(ctx)) }
// POST /qrcode/generate-key func qrCodeKeyGenerateHandler(w http.ResponseWriter, r *http.Request) { if strings.ToUpper(r.Method) != "POST" { http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) return } c := appengine.NewContext(r) var tmpKey string // Check for duplicated clientKey for { tmpKey = genKey() qry := datastore.NewQuery("ClientKey").Filter("Id =", tmpKey).Filter("Used =", false) cnt, _ := qry.Count(c) if cnt == 0 { break } } clientKey := ClientKey{ Id: tmpKey, PrinterID: "label_printer_0", Used: false, CTime: time.Now(), } _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "ClientKey", nil), &clientKey) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprint(w, tmpKey) }
func (t *Site) key(c appengine.Context) *datastore.Key { if t.Id == 0 { t.Created = time.Now() return datastore.NewIncompleteKey(c, "Site", defaultSiteList(c)) } return datastore.NewKey(c, "Site", "", t.Id, defaultSiteList(c)) }
/* * Records the important parts of a submit request and * puts it into the datastore so that it can be seen in the log */ func recordRequest(w http.ResponseWriter, r *http.Request, a bool, resp string) { stringpath := fmt.Sprintf("%#v", r.URL.Path) rawquery := fmt.Sprintf("%#v", r.URL.RawQuery) passwordstring := fmt.Sprintf("%#v", r.FormValue("password")) c := appengine.NewContext(r) var acceptedString string if a { acceptedString = "true" } else { acceptedString = "false" } req := RequestRecord{ RemoteAddr: r.RemoteAddr, Host: r.Host, Path: stringpath, RawQuery: rawquery, Time: time.Now(), Password: passwordstring, Accepted: acceptedString, ResponsePassword: resp, } _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Record", nil), &req) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
func CreatePermLink(ctx appengine.Context, input *MatchInput) (string, error) { //Create SHA-1 hash var bytes bytes.Buffer enc := gob.NewEncoder(&bytes) err := enc.Encode(input) if err != nil { return "", err } hashOutput := sha1.Sum(bytes.Bytes()) strHash := fmt.Sprintf("%x", hashOutput[:]) strHash = strHash[:permLinkLength] //Only store if hash doesn't already exist num, err := datastore.NewQuery("perm_link").Filter("Hash =", strHash).Count(ctx) if err != nil { return "", err } if num > 0 { return strHash, nil } //If hash does not exist, store in datastore entity := &PermLinkStore{*input, strHash} _, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "perm_link", nil), entity) if err != nil { return "", err } return strHash, nil }
func saveHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) c.Debugf("The message: %v", "saveHandler") var books []*Book if r.FormValue("exec") == "store" { c.Debugf("The message: %v", "post Stored") c.Debugf("The title: %v", r.FormValue("title")) c.Debugf("The author: %v", r.FormValue("author")) c.Debugf("The contents: %v", r.FormValue("contents")) book := Book{ Title: r.FormValue("title"), Author: r.FormValue("author"), Contents: r.FormValue("contents"), } key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "book", nil), &book) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } c.Debugf("The key: %v", key) renderTemplate(w, "view", books) } else { renderTemplate(w, "save", books) } }
func (q *Quote) key(ctx appengine.Context) *datastore.Key { if q.ID == 0 { q.Created = time.Now() return datastore.NewIncompleteKey(ctx, "Quote", defaultQuotes(ctx)) } return datastore.NewKey(ctx, "Quote", "", q.ID, defaultQuotes(ctx)) }
func getAndStoreTerms(context appengine.Context) ([]Term, error) { responseBody, err := runApiRequest(context, "/Terms") if err != nil { context.Infof("Failed loading the terms!") context.Infof(err.Error()) return nil, err } context.Infof("About to unmarshal: %s", string(responseBody)) var termsResponse TermsOverallResponse err = json.Unmarshal(responseBody, &termsResponse) if err != nil { context.Infof("Couldn't unmarshal the terms response") context.Infof(err.Error()) return nil, err } termsQuery := datastore.NewQuery("Term").KeysOnly() termKeys, err := termsQuery.GetAll(context, nil) if err != nil { context.Infof("There was a problem loading the existing terms from the datastore") context.Infof(err.Error()) return nil, err } for _, termKey := range termKeys { datastore.Delete(context, termKey) } for _, term := range termsResponse.OverallResponse.Terms { datastore.Put(context, datastore.NewIncompleteKey(context, "Term", nil), &term) } return termsResponse.OverallResponse.Terms, nil }
func doCreateNew(w http.ResponseWriter, r *http.Request) { user := r.FormValue("user") if user == "" { //empty values or variables not sended. Very basic prevention fmt.Fprintf(w, "<html>Error: error in arguments. Go <a href='/login.do' >Back</a></html>") return } c := appengine.NewContext(r) q := datastore.NewQuery("User"). Filter("Username = "******"<html>Username already exists. <a href='/login.docreate' >Go back</a></html>") return } var theuser User theuser.Username = user theuser.Creation = time.Now() theuser.Tok3nKey = "" key := datastore.NewIncompleteKey(c, "User", nil) key, err := datastore.Put(c, key, &theuser) if err != nil { fmt.Fprintf(w, "Error: %v", err) return } fmt.Fprintf(w, "<html>New user (%s) added. <a href='/login.do'>Go login now</a>.</html>", user) }
// [START func_sign] func sign(w http.ResponseWriter, r *http.Request) { // [START new_context] c := appengine.NewContext(r) // [END new_context] g := Greeting{ Content: r.FormValue("content"), Date: time.Now(), } // [START if_user] if u := user.Current(c); u != nil { g.Author = u.String() } // We set the same parent key on every Greeting entity to ensure each Greeting // is in the same entity group. Queries across the single entity group // will be consistent. However, the write rate to a single entity group // should be limited to ~1/second. key := datastore.NewIncompleteKey(c, "Greeting", guestbookKey(c)) _, err := datastore.Put(c, key, &g) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/", http.StatusFound) // [END if_user] }
func AddData(img models.Image, c appengine.Context) (string, error) { //create a new key for our data key := datastore.NewIncompleteKey(c, "image", nil) //store in the datastore a, err := datastore.Put(c, key, &img) return a.String(), err }
// POST http://localhost:8080/profiles // {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} // func (u *ProfileApi) insert(r *restful.Request, w *restful.Response) { c := appengine.NewContext(r.Request) // Marshall the entity from the request into a struct. p := new(Profile) err := r.ReadEntity(&p) if err != nil { w.WriteError(http.StatusNotAcceptable, err) return } // Ensure we start with a sensible value for this field. p.LastModified = time.Now() // The profile belongs to this user. p.Email = user.Current(c).String() k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "profiles", nil), p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Let them know the location of the newly created resource. // TODO: Use a safe Url path append function. w.AddHeader("Location", u.Path+"/"+k.Encode()) // Return the resultant entity. w.WriteHeader(http.StatusCreated) w.WriteEntity(p) }
// uploadHandler handles the image upload and stores a new Overlay in the // datastore. If successful, it writes the Overlay's key to the response. func uploadHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) *appError { // Handle the upload, and get the image's BlobKey. blobs, _, err := blobstore.ParseUpload(r) if err != nil { return appErrorf(err, "could not parse blobs from blobstore upload") } b := blobs["overlay"] if len(b) < 1 { return appErrorf(nil, "could not find overlay blob") } bk := b[0].BlobKey // Fetch image from blob store to find its width and height. m, err := imageBlob(c, bk) if err != nil { return appErrorf(err, "could not get image") } // Create and store a new Overlay in the datastore. o := &Overlay{ Owner: user.Current(c).ID, Image: bk, Width: m.Bounds().Dx(), Height: m.Bounds().Dy(), } k := datastore.NewIncompleteKey(c, "Overlay", nil) k, err = datastore.Put(c, k, o) if err != nil { return appErrorf(err, "could not save new overlay to datastore") } // It will be known hereafter by its datastore-provided key. fmt.Fprintf(w, "%s", k.Encode()) return nil }
func create(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) resource, _, err := get_vars(r) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } room, err := get_room(r) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } k := datastore.NewKey(c, "room", "0", room.Id) fmt.Fprintf(w, "%v", k) key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "room", nil), &room) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprintf(w, "Created %v:\n%v\nKey:%v\n", resource, room, key) }
func register(w http.ResponseWriter, req *http.Request) { req.ParseForm() context := appengine.NewContext(req) team := Team{ Date: time.Now(), Name: req.FormValue("name"), Email: req.FormValue("email"), Phonenumber: req.FormValue("phone"), PartnerName: req.FormValue("partner-name"), PartnerEmail: req.FormValue("partner-email"), PartnerPhonenumber: req.FormValue("partner-phone"), Tech: strings.Join(req.Form["tech"], ","), TeamDescrition: req.FormValue("descript"), TeamWish: req.FormValue("wish"), } // TODO make vaildater key := datastore.NewIncompleteKey(context, "3rd", getDataStoreKey(context)) _, err := datastore.Put(context, key, &team) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } else { view.Render(w, "main", RenderData{Mode: "pc"}) return } }
func joinChannel(c appengine.Context, w http.ResponseWriter, channelId string) { if len(channelId) == 0 { http.Error(w, "Invalid channel ID", http.StatusBadRequest) return } peers, err := getPeersInChannel(c, channelId) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } parentKey := makeRootChannelKey(c, channelId) newEntryKey := datastore.NewIncompleteKey(c, "channelEntry", parentKey) newEntry := new(channelEntry) newEntry.PeerID = generatePeerId() if _, err := datastore.Put(c, newEntryKey, newEntry); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } encoder := json.NewEncoder(w) encoder.Encode(struct { PeerID string Peers []string }{newEntry.PeerID, peers}) }
// jsonData.Tags map[string][]Word // take a slice of ids as appeared in json and slice of // keys as now stored for items with tags // add any tags for these items that were in json but not yet stored func (self *importer) importTags(ids []string, keys []*datastore.Key) { for index, parentKey := range keys { parentId := ids[index] destId := keys[index].Encode() if importTags, ok := self.jsonData.Tags[parentId]; ok { var myTags map[string]bool // if this item doesn't have a tags collection yet, // add it var found bool if myTags, found = self.allTags[destId]; !found { myTags = make(map[string]bool) self.allTags[destId] = myTags } // go through tags from json for _, tag := range importTags { if _, found := myTags[tag.Word]; !found { // this tag doesn't exist yet, add to our list self.newTags = append(self.newTags, &Word{"", tag.Word}) newTagKey := datastore.NewIncompleteKey(self.c, "Tags", parentKey) self.newTagKeys = append(self.newTagKeys, newTagKey) myTags[tag.Word] = true } } } } }
func register(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) g := Member{ Usern: r.FormValue("usern"), Name: r.FormValue("name"), Passwd: r.FormValue("passwd"), Repasswd: r.FormValue("repasswd"), Phone: r.FormValue("phone"), Email: r.FormValue("email"), Study: r.FormValue("study"), Address: r.FormValue("address"), Date: datastore.SecondsToTime(time.Seconds()), } if g.Passwd == g.Repasswd && g.Usern != "" && g.Name != "" && g.Phone != "" && g.Email != "" { _, err := datastore.Put(c, datastore.NewIncompleteKey("Member"), &g) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } } else { http.Redirect(w, r, "/signin", http.StatusFound) } http.Redirect(w, r, "/view", http.StatusFound) }