作者:thraxi
项目:gofaktu
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)
}
}
作者:reedlabot
项目:scribblevin
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
}
作者:cmc33333
项目:fragspac
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),
},
}
}
作者:676
项目:goblo
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)
}
作者:Mononof
项目:automatic-diar
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", "/")
}
作者:wickedchicke
项目:blar
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
}
作者:neowin
项目:mscloud-emende
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")
}
}
作者:cmc33333
项目:fragspac
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._%\-+][email protected][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)
}
}
作者:Tok3
项目:tok3nsdkgo_demoA
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 = ", user)
if count, _ := q.Count(c); count > 0 { //Verify the previous existence of the user
fmt.Fprintf(w, "<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)
}
作者:nkort
项目:UmichClassChecke
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
}
作者:ashishdotanan
项目:sdcr
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))
}
作者:pg
项目:checklis
// 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
}
作者:ninneman
项目:dynamicfa
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))
}
作者:jchor
项目:websit
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)
}
作者:CNDonn
项目:scop
// 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)
}
作者:hakchi
项目:g
// [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]
}
作者:atomath
项目:braille-printe
// 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)
}
作者:vorcigerni
项目:cookieryb
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))
}
作者:postfi
项目:NFC-Securit
/*
* 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
}
}
作者:thaJezta
项目:reg
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
}