func put(rw http.ResponseWriter, req *http.Request) { c := appengine.NewContext(req) u := user.Current(c) m := req.FormValue("message") s := req.FormValue("encoded_key") // fmt.Fprintf(rw, "Key 1: %v", s) p := req.FormValue("parent_key") var t, ut string var op bool var k *datastore.Key // make/decode keys if s == "" { if p == "" { k = datastore.NewIncompleteKey(c, "post", nil) op = true } else { pk, err := datastore.DecodeKey(p) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } k = datastore.NewIncompleteKey(c, "post", pk) op = false } t = time.Now().Format("Jan 2, 2006 3:04 PM") ut = "" } else { k, err := datastore.DecodeKey(s) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } mypost := Post{} err = datastore.Get(c, k, &mypost) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } ut = time.Now().Format("Jan 2, 2006 3:04 PM") t = mypost.PostDate op = mypost.OP } // data := url.Values{} // data.Set("encoded_key", k.Encode()) // r, _ := http.NewRequest("POST", "/view", bytes.NewBufferString(data.Encode())) newpost := Post{Author: u.String(), Message: m, UpdateDate: ut, PostDate: t, OP: op} _, err := datastore.Put(c, k, &newpost) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } // http.Redirect(rw, r, "/view", http.StatusOK) http.Redirect(rw, req, "/", http.StatusTemporaryRedirect) }
// SaveBoardState commits the state to the datastore func SaveBoardState(c context.Context, state *BoardState) (*BoardState, error) { sessionKey, err := datastore.DecodeKey(state.SessionID) if err != nil { return nil, err } stateModel := &boardStateModel{} stateModel.parentKey = sessionKey stateModel.lastModified = time.Now() stateModel.key, err = datastore.Put(c, datastore.NewIncompleteKey(c, "BoardState", stateModel.parentKey), stateModel) if err != nil { return nil, err } // Initialize the result result := &BoardState{ ID: stateModel.key.Encode(), SessionID: stateModel.parentKey.Encode(), LastModified: time.Now(), Players: make(map[string]*Player), } // Save the players for k, v := range state.Players { p := &playerModel{ Name: k, Location: v.Location, } p.parentKey = stateModel.key p.key, err = datastore.Put(c, datastore.NewIncompleteKey(c, "PlayerState", p.parentKey), p) if err != nil { return nil, err } for _, card := range v.Hand { cardModel := &cardModel{ Name: card.Name, Color: card.Color, } cardModel.parentKey = p.key cardModel.key, err = datastore.Put(c, datastore.NewIncompleteKey(c, "PlayerCard", p.parentKey), cardModel) if err != nil { return nil, err } } // Added player to result result.Players[k] = &Player{ Location: p.Location, Hand: v.Hand, } } return result, nil }
func example6() { // [START parent] // Create Employee entity employee := &Employee{ /* ... */ } employeeKey, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Employee", nil), employee) // Use Employee as Address entity's parent // and save Address entity to datastore address := &Address{ /* ... */ } addressKey := datastore.NewIncompleteKey(ctx, "Address", employeeKey) _, err = datastore.Put(ctx, addressKey, address) // [END parent] _ = 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) }
//WriteLinkTweet writes a given Tweet to the datastore func (mb MapBuilder) writeLinkTweet(tweets <-chan anaconda.Tweet, wg *sync.WaitGroup) { defer wg.Done() var keys []*datastore.Key var values []*int64 for tweet := range tweets { key := datastore.NewIncompleteKey(mb.c, linkTweetKind, getTweetKey(mb.c)) keys = append(keys, key) values = append(values, &tweet.Id) } err := datastore.RunInTransaction(mb.c, func(c context.Context) error { _, err := datastore.PutMulti(c, keys, values) if err != nil { log.Errorf(c, "Failed to write LinkTweet to datastore. %v", err.Error()) return err } return nil }, nil) if err != nil { log.Errorf(mb.c, "Failed to write LinkTweet to datastore. %v", err.Error()) } }
func APIKeyAddHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) u := user.Current(c) if u == nil { loginUrl, _ := user.LoginURL(c, r.URL.RequestURI()) http.Redirect(w, r, loginUrl, http.StatusFound) return } else { if !u.Admin { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not an admin. Go away.")) } else { key := randomString(26) owner := r.FormValue("owner") if owner == "" { w.Write([]byte("You forgot a parameter.")) } else { apiKey := APIKey{ APIKey: key, OwnerEmail: owner, } dkey := datastore.NewIncompleteKey(c, "APIKey", nil) _, err := datastore.Put(c, dkey, &apiKey) if err != nil { w.Write([]byte(fmt.Sprintf("error! %s", err.Error()))) } else { w.Write([]byte(key)) } } } } }
func warmupHandler(c *echo.Context) error { if appengine.IsDevAppServer() { photographers := []Photographer{ {1, "Mr Canon"}, {2, "Miss Nikon"}, {3, "Mrs Pentax"}, {4, "Ms Sony"}, } // create some dummy data for m := 1; m <= 12; m++ { for d := 1; d < 28; d++ { taken := time.Date(2015, time.Month(m), d, 12, 0, 0, 0, time.UTC) id := rand.Int31n(4) photographer := photographers[id] p := Photo{ Photographer: photographer, Uploaded: time.Now().UTC(), Width: 8000, Height: 6000, Taken: taken, } k := datastore.NewIncompleteKey(c, "photo", nil) nds.Put(c, k, &p) } } } return c.NoContent(http.StatusOK) }
func getOrCreateChat(c context.Context, fbChatID int64, keyBuf **datastore.Key) (*Chat, error) { results := make([]Chat, 0, 1) keys, err := datastore.NewQuery("Chat"). Filter("FacebookChatID =", fbChatID).Limit(1).GetAll(c, &results) if err != nil { return nil, err } var resultChat *Chat var resultKey *datastore.Key if len(keys) == 0 { incKey := datastore.NewIncompleteKey(c, "Chat", nil) resultChat = &Chat{ FacebookChatID: fbChatID, ChatName: "", } resultKey, err = datastore.Put(c, incKey, resultChat) if err != nil { return nil, err } } else { resultKey = keys[0] resultChat = &results[0] } if keyBuf != nil { *keyBuf = resultKey } return resultChat, nil }
// CreateVenueHandler makes a new venue and saves it to the datastore func CreateVenueHandler(w util.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) var venueData Venue if err := json.NewDecoder(r.Body).Decode(&venueData); err != nil { log.Println("Unable to decode create venue data:", err.Error()) http.Error(w, "Unable to decode JSON request body", http.StatusBadRequest) return } if venueData.Name == "" { http.Error(w, `must provide "name" field when creating a venue`, http.StatusBadRequest) return } key := datastore.NewIncompleteKey(c, "Venues", nil) newKey, err := datastore.Put(c, key, &venueData) if err != nil { w.WriteJSON(nil, err) return } venueData.ID = newKey.IntID() w.WriteJSON(&venueData, nil) }
// this will generate some random data for the given day // 24 * 12 on appengine (288) // 24 only on development func generateRandom(c context.Context, day time.Time) error { var x int if appengine.IsDevAppServer() { x = 1 } else { x = 12 } keys := make([]*datastore.Key, 24*x) photos := make([]*Photo, 24*x) id := 0 for h := 0; h < 24; h++ { taken := day.Add(time.Duration(h) * time.Hour) for i := 0; i < x; i++ { photographer := photographers[rand.Int31n(4)] photos[id] = &Photo{ Photographer: photographer, Uploaded: time.Now().UTC(), Width: 8000, Height: 6000, Taken: taken, TakenDay: day, } keys[id] = datastore.NewIncompleteKey(c, "photo", nil) id++ } } nds.PutMulti(c, keys, photos) return nil }
// Put will put this Submission into Datastore using the given key. func (ƨ Submission) Put(ctx context.Context, key *datastore.Key) (*datastore.Key, error) { if key != nil { return datastore.Put(ctx, key, &ƨ) } return datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Submission", nil), &ƨ) }
func adminNewTask(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) asInt := func(s string) int { i, err := strconv.Atoi(s) if err != nil { panic(err) } return i } task := Task{ Name: r.FormValue("name"), Description: r.FormValue("description"), Assignee: r.FormValue("assignee"), RType: r.FormValue("rtype"), Automatic: mightParseBool(r.FormValue("automatic")), Period: asInt(r.FormValue("period")), Value: asInt(r.FormValue("value")), Next: time.Now().UTC(), } k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Task", nil), &task) if err != nil { log.Warningf(c, "Error storing task: %v", err) panic(err) } log.Infof(c, "Stored new thing with key %v", k) http.Redirect(w, r, "/admin/tasks/", 307) }
// insert tweet func putTweet(req *http.Request, tweet *Tweet) error { ctx := appengine.NewContext(req) key := datastore.NewIncompleteKey(ctx, "Tweet", nil) _, err := datastore.Put(ctx, key, tweet) return err // you can use memcache also to improve your consistency }
func create2Handler(w http.ResponseWriter, r *http.Request) { strTitle := r.FormValue("title") strLink := r.FormValue("link") // fmt.Fprint(w, "go title: ", strTitle) // fmt.Fprint(w, "link: ", strLink) //TODO error checking for the title and link c := appengine.NewContext(r) u := user.Current(c) //TODO error checking for user? //TODO check random thread against an already existing one rand.Seed(time.Now().UnixNano()) newThreadId := rand.Int63() newSubmission := WebSubmission{ Title: strTitle, Link: strLink, SubmitBy: u.String(), Thread: newThreadId, //TODO create random thread id SubmitDateTime: time.Now(), SubmissionDesc: "", Score: 0, } _, err := datastore.Put(c, datastore.NewIncompleteKey(c, WebSubmissionEntityName, nil), &newSubmission) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/", http.StatusFound) }
// Put will put this JunitTestResult into Datastore using the given key. func (ƨ JunitTestResult) Put(ctx context.Context, key *datastore.Key) (*datastore.Key, error) { if key != nil { return datastore.Put(ctx, key, &ƨ) } return datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "JunitTestResult", nil), &ƨ) }
func submitAddHandler(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) if err := r.ParseForm(); err != nil { serveErr(ctx, err, w) return } success, err := recaptchaCheck(ctx, r.FormValue("g-recaptcha-response"), r.RemoteAddr) if err != nil { serveErr(ctx, err, w) return } if !success { log.Warningf(ctx, "reCAPTCHA check failed") failedTmpl.ExecuteTemplate(w, "base", nil) return } sub := Submission{ URL: template.URL(strings.TrimSpace(r.FormValue("url"))), Submitted: time.Now(), } if _, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Submission", nil), &sub); err != nil { serveErr(ctx, err, w) return } thanksTmpl.ExecuteTemplate(w, "base", nil) }
// CreateVenueDishHandler creates a new dish based on the request body func CreateVenueDishHandler(w util.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) var dishData Dish if err := json.NewDecoder(r.Body).Decode(&dishData); err != nil { log.Println("Unable to decode create dish data:", err.Error()) http.Error(w, "Unable to decode JSON request body", http.StatusBadRequest) return } venueID, err := util.GetIntParam(r, "venue_id", 0) if !VenueExists(c, venueID) { http.Error(w, "provided venue_id does not exist", http.StatusBadRequest) return } dishData.VenueID = venueID if dishData.Name == "" { http.Error(w, `must provide "name" field when creating a dish`, http.StatusBadRequest) return } key := datastore.NewIncompleteKey(c, "Dishes", nil) newKey, err := datastore.Put(c, key, &dishData) if err != nil { w.WriteJSON(nil, err) return } dishData.ID = newKey.IntID() w.WriteJSON(&dishData, nil) }
func (t *Todo) key(c context.Context) *datastore.Key { if t.Id == 0 { t.Created = time.Now() return datastore.NewIncompleteKey(c, "Todo", DefaultTodoList(c)) } return datastore.NewKey(c, "Todo", "", t.Id, DefaultTodoList(c)) }
func putTweet(req *http.Request, user *User, tweet *Tweet) error { ctx := appengine.NewContext(req) userKey := datastore.NewKey(ctx, "Users", user.UserName, 0, nil) key := datastore.NewIncompleteKey(ctx, "Tweets", userKey) _, err := datastore.Put(ctx, key, tweet) return err }
func (s *MigrationService) run(ctx context.Context, m *Migration) error { if m.RunAt.IsZero() { m.RunAt = time.Now() } if m.Version.IsZero() { return errors.New("cannot run migration without version") } // TODO: Pipe rootKey through with context. rootKey := datastore.NewKey(ctx, "Root", "root", 0, nil) k := datastore.NewIncompleteKey(ctx, "Migration", rootKey) err := m.Run(ctx, s) if err != nil { return err } _, err = datastore.Put(ctx, k, m) if err != nil { return err } return nil }
func TestBasicUsage2(t *testing.T) { c, closer, err := aetest.NewContext() if err != nil { t.Fatal(err) } defer closer() src := &a.Sample{"Foo!"} key := datastore.NewIncompleteKey(c, "Sample", nil) _, err = datastore.Put(c, key, src) if err != nil { t.Fatal(err) } builder := a.NewSampleQueryBuilder() builder.Foo.GreaterThan("Foo").KeysOnly().Limit(3) iter := builder.Query().Run(c) for { key, err = iter.Next(nil) if err == datastore.Done { break } else if err != nil { t.Fatal(err) } src := &a.Sample{} err = datastore.Get(c, key, src) if err != nil { t.Fatal(err) } t.Logf("key: %#v, entity: %#v", key, src) } }
// Put will put this Challenge into Datastore using the given key. func (ƨ Challenge) Put(ctx context.Context, key *datastore.Key) (*datastore.Key, error) { if key != nil { return datastore.Put(ctx, key, &ƨ) } return datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Challenge", nil), &ƨ) }
func buttonClickedPage(w http.ResponseWriter, r *http.Request) { click := &clickData{ IPAddress: r.RemoteAddr, } c := appengine.NewContext(r) key := datastore.NewIncompleteKey(c, "Click", clickKey(c)) _, err := datastore.Put(c, key, click) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } clickCount, err := datastore.NewQuery("Click").Count(c) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } stats := &buttonStats{ Clicks: clickCount, } w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-cache") err = json.NewEncoder(w).Encode(stats) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
func handleIndex(res http.ResponseWriter, req *http.Request) { if req.Method == "POST" { term := req.FormValue("term") definition := req.FormValue("definition") ctx := appengine.NewContext(req) key := datastore.NewIncompleteKey(ctx, "Word", nil) entity := Word{ Term: term, Definition: definition, } _, err := datastore.Put(ctx, key, &entity) if err != nil { http.Error(res, err.Error(), 500) return } } res.Header().Set("Content-Type", "text/html") fmt.Fprintln(res, ` <form method="POST" action="/words/"> <input type="text" name="term"> <textarea name="definition"></textarea> <input type="submit"> </form>`) }
// Write the expo to the datastore, returns the key or an error func SaveExpo(c context.Context, expo *Expo) (*datastore.Key, error) { key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "expo", nil), expo) if err != nil { return nil, err } return key, nil }
func tweetProcess(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { ctx := appengine.NewContext(req) memItem, err := getSession(req) if err != nil { log.Infof(ctx, "Attempt to post tweet from logged out user") http.Error(res, "You must be logged in", http.StatusForbidden) return } // declare a variable of type user // initialize user with values from memcache item var user User json.Unmarshal(memItem.Value, &user) // declare a variable of type tweet // initialize it with values tweet := Tweet{ Msg: req.FormValue("tweet"), Time: time.Now(), } userKey := datastore.NewKey(ctx, "Users", user.UserName, 0, nil) key := datastore.NewIncompleteKey(ctx, "Tweets", userKey) _, err = datastore.Put(ctx, key, &tweet) if err != nil { log.Errorf(ctx, "error adding todo: %v", err) http.Error(res, err.Error(), 500) return } // redirect http.Redirect(res, req, "/", 302) }
func Post(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") ctx := appengine.NewContext(r) dec := json.NewDecoder(r.Body) var list model.List if err := dec.Decode(&list); err != nil { jsonError.NewBadRequest(err.Error()).HttpError(w) return } key := datastore.NewIncompleteKey(ctx, "List", nil) createdAt := time.Now() list.Id = key list.CreatedAt = createdAt list.ModifiedAt = createdAt list.Owner = getUser(ctx) for _, item := range list.Items { item.CreatedAt = createdAt item.ModifiedAt = createdAt } if _, err := datastore.Put(ctx, key, &list); err != nil { jsonError.NewInternalServerError(err.Error()).HttpError(w) return } enc := json.NewEncoder(w) if err := enc.Encode(list); err != nil { jsonError.NewInternalServerError(err.Error()).HttpError(w) return } }
func handleSign(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "POST requests only", http.StatusMethodNotAllowed) return } c := appengine.NewContext(r) if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } g := &Greeting{ Content: r.FormValue("content"), Date: time.Now(), } if u := user.Current(c); u != nil { g.Author = u.String() } key := datastore.NewIncompleteKey(c, "Greeting", guestbookKey(c)) if _, err := datastore.Put(c, key, g); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Redirect with 303 which causes the subsequent request to use GET. http.Redirect(w, r, "/", http.StatusSeeOther) }
func ActivityLogPost(c context.Context, activityLog *ActivityLog) error { // generate new key key := datastore.NewIncompleteKey(c, "ActivityLog", nil) //store in database _, err := datastore.Put(c, key, activityLog) return err }
func makeTweet(ctx context.Context, tweet *Tweet) error { key := datastore.NewIncompleteKey(ctx, "Tweet", nil) key, err := datastore.Put(ctx, key, tweet) if err == nil { tweet.ID = key.IntID() } return err }