本文整理汇总了Golang中google/golang.org/appengine/datastore.DecodeKey函数的典型用法代码示例。如果您正苦于以下问题:Golang DecodeKey函数的具体用法?Golang DecodeKey怎么用?Golang DecodeKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DecodeKey函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: PostSubmission
// PostSubmission creates a new submission.
func PostSubmission(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
p, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
if r.Method != "POST" {
return http.StatusMethodNotAllowed, nil
}
resultKey, err := datastore.DecodeKey(mux.Vars(r)["resultKey"])
if !util.HasParent(p.UserKey, resultKey) {
return http.StatusBadRequest, errors.New("cannot submit answer for other users")
}
taskKey, err := datastore.DecodeKey(mux.Vars(r)["taskKey"])
// Note: When more task kinds are added, see controllers.CreateFinalResult.
switch taskKey.Kind() {
case model.CodeTaskKind:
return runner.HandleCodeSubmission(ctx, w, r, resultKey, taskKey)
// TODO(victorbalan, flowlo): Use correct kind when possible.
case "QuestionTask":
return http.StatusInternalServerError, errors.New("question submissions are not yet implemented")
default:
return http.StatusBadRequest, errors.New("Unknown submission kind.")
}
}
开发者ID:tudorgergely,项目名称:api,代码行数:28,代码来源:submission.go
示例2: put
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)
}
开发者ID:SiroDiaz,项目名称:csuf,代码行数:58,代码来源:BulletinBoard.go
示例3: AddEvent
// AddEvent - Add an Event and save to Datastore
func AddEvent(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
// Set the timestamps
at := time.Now()
const timeformat = "2006-01-02 15:04:05 -0700"
st, _ := time.Parse(timeformat, r.FormValue("start_time"))
et, _ := time.Parse(timeformat, r.FormValue("end_time"))
dt, _ := time.Parse(timeformat, r.FormValue("door_time"))
// Create the event object
e1 := Event{
StartDate: st,
EndDate: et,
DateAdded: at,
DoorTime: dt,
Name: r.FormValue("headline"),
Description: r.FormValue("description"),
URL: r.FormValue("event_url"),
Image: r.FormValue("poster_file"),
}
// Load the Venue Key
if len(r.FormValue("venue")) > 0 {
venue, err := datastore.DecodeKey(r.FormValue("venue"))
fmt.Fprintf(w, "%+v", venue)
if err != nil {
JSONError(&w, err.Error())
return
}
e1.Venue = venue
}
// Load the Promoter Key
if len(r.FormValue("promoter")) > 0 {
promoter, err := datastore.DecodeKey(r.FormValue("promoter"))
if err != nil {
JSONError(&w, err.Error())
return
}
e1.Promoter = promoter
fmt.Fprintf(w, "%+v", e1)
}
// Add the event to the Datastore
k, err := e1.Store(ctx)
if err != nil {
JSONError(&w, err.Error())
return
}
e1.DatastoreKey = *k
return
}
开发者ID:capnfuzz,项目名称:qrtickets,代码行数:55,代码来源:event.go
示例4: ServeHTTP
func (h urlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := h.getContext(r)
ds := appwrap.NewAppengineDatastore(c)
monitorTimeout := time.Minute * 30
if appengine.IsDevAppServer() {
monitorTimeout = time.Second * 10
}
if strings.HasSuffix(r.URL.Path, "/map-monitor") || strings.HasSuffix(r.URL.Path, "/reduce-monitor") {
if jobKeyStr := r.FormValue("jobKey"); jobKeyStr == "" {
http.Error(w, "jobKey parameter required", http.StatusBadRequest)
} else if jobKey, err := datastore.DecodeKey(jobKeyStr); err != nil {
http.Error(w, fmt.Sprintf("invalid jobKey: %s", err.Error()),
http.StatusBadRequest)
} else if strings.HasSuffix(r.URL.Path, "/map-monitor") {
w.WriteHeader(mapMonitorTask(c, ds, h.pipeline, jobKey, r, monitorTimeout))
} else {
w.WriteHeader(reduceMonitorTask(c, ds, h.pipeline, jobKey, r, monitorTimeout))
}
return
}
var taskKey *datastore.Key
var err error
if taskKeyStr := r.FormValue("taskKey"); taskKeyStr == "" {
http.Error(w, "taskKey parameter required", http.StatusBadRequest)
return
} else if taskKey, err = datastore.DecodeKey(taskKeyStr); err != nil {
http.Error(w, fmt.Sprintf("invalid taskKey: %s", err.Error()),
http.StatusBadRequest)
return
}
if strings.HasSuffix(r.URL.Path, "/reduce") {
reduceTask(c, ds, h.baseUrl, h.pipeline, taskKey, w, r)
} else if strings.HasSuffix(r.URL.Path, "/map") {
mapTask(c, ds, h.baseUrl, h.pipeline, taskKey, w, r)
} else if strings.HasSuffix(r.URL.Path, "/mapstatus") ||
strings.HasSuffix(r.URL.Path, "/reducestatus") {
updateTask(ds, taskKey, "", 0, r.FormValue("msg"), nil)
} else {
http.Error(w, "unknown request url", http.StatusNotFound)
return
}
}
开发者ID:pendo-io,项目名称:mapreduce,代码行数:49,代码来源:mapreduce.go
示例5: deleteData
func deleteData(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
keyVal := req.FormValue("keyVal")
key, err := datastore.DecodeKey(keyVal)
if err != nil {
http.Error(res, "Invalid data", http.StatusBadRequest)
log.Warningf(ctx, err.Error())
return
}
var l list
err = datastore.Get(ctx, key, &l)
if err != nil {
http.Error(res, "Invalid data", http.StatusBadRequest)
log.Warningf(ctx, err.Error())
return
}
if l.Owner != u.Email {
http.Error(res, "Not authorized to delete this entry", http.StatusUnauthorized)
log.Warningf(ctx, err.Error())
return
}
err = datastore.Delete(ctx, key)
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
}
开发者ID:CodingDance,项目名称:GolangTraining,代码行数:29,代码来源:main.go
示例6: ChallengeByKey
// ChallengeByKey loads a challenge by key.
func ChallengeByKey(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
if r.Method != "GET" {
return http.StatusMethodNotAllowed, nil
}
p, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
key, err := datastore.DecodeKey(mux.Vars(r)["key"])
if err != nil {
return http.StatusInternalServerError, err
}
var challenge model.Challenge
err = datastore.Get(ctx, key, &challenge)
if err != nil {
return http.StatusInternalServerError, err
}
e := json.NewEncoder(w)
if parent := p.UserKey.Parent(); parent == nil {
// The current user is a coder so we must also create a result.
e.Encode(challenge.Key(key))
} else {
// TODO(pbochis): If a company representativemakes the request
// we also include Tasks in the response.
e.Encode(challenge.Key(key))
}
return http.StatusOK, nil
}
开发者ID:tudorgergely,项目名称:api,代码行数:35,代码来源:challenge.go
示例7: GetChallengesForCompany
// GetChallengesForCompany queries all the challenges defined by a company.
func GetChallengesForCompany(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
if r.Method != "GET" {
return http.StatusMethodNotAllowed, nil
}
_, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
key, err := datastore.DecodeKey(mux.Vars(r)["key"])
if err != nil {
return http.StatusInternalServerError, err
}
var challenges model.Challenges
keys, err := model.NewQueryForChallenge().
Ancestor(key).
GetAll(ctx, &challenges)
if err != nil {
return http.StatusInternalServerError, err
}
json.NewEncoder(w).Encode(challenges.Key(keys))
return http.StatusOK, nil
}
开发者ID:tudorgergely,项目名称:api,代码行数:29,代码来源:challenge.go
示例8: read
// GET http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM
//
func (u ProfileApi) read(r *restful.Request, w *restful.Response) {
c := appengine.NewContext(r.Request)
// Decode the request parameter to determine the key for the entity.
k, err := datastore.DecodeKey(r.PathParameter("profile-id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Retrieve the entity from the datastore.
p := Profile{}
if err := datastore.Get(c, k, &p); err != nil {
if err.Error() == "datastore: no such entity" {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Check we own the profile before allowing them to view it.
// Optionally, return a 404 instead to help prevent guessing ids.
// TODO: Allow admins access.
if p.Email != user.Current(c).String() {
http.Error(w, "You do not have access to this resource", http.StatusForbidden)
return
}
w.WriteEntity(p)
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:33,代码来源:main.go
示例9: Handle
// Handle performs an upgrade from HTTP to WebSocket. It hijacks the connection
// and registers it in the global pool.
func Handle(w http.ResponseWriter, r *http.Request) {
m := r.URL.Query()
result := m.Get("result")
if result == "" {
http.Error(w, "Bad Request: missing parameter \"result\"", http.StatusBadRequest)
return
}
key, err := datastore.DecodeKey(result)
if err != nil {
http.Error(w, "Bad Request: cannot decode \"result\"", http.StatusBadRequest)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
// NOTE: Returning a HTTP error is done by upgrader.
return
}
conns.Lock()
conns.m[ktoi(key)] = conn
conns.Unlock()
reader(conn)
}
开发者ID:pbochis,项目名称:api,代码行数:29,代码来源:ws.go
示例10: adminUpdateTask
func adminUpdateTask(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
tid := r.FormValue("taskKey")
k, err := datastore.DecodeKey(tid)
if err != nil {
panic(err)
}
task := &Task{}
if err := datastore.Get(c, k, task); err != nil {
log.Warningf(c, "Error getting task %v: %v", k, err)
http.Error(w, err.Error(), 404)
return
}
task.Name = r.FormValue("name")
task.Description = r.FormValue("description")
task.Value = asInt(r.FormValue("value"))
task.Period = asInt(r.FormValue("period"))
task.Disabled = mightParseBool(r.FormValue("disabled"))
task.Automatic = mightParseBool(r.FormValue("automatic"))
task.Assignee = r.FormValue("assignee")
if _, err := datastore.Put(c, k, task); err != nil {
log.Warningf(c, "Error storing task %v, %+v: %v", k, task, err)
http.Error(w, err.Error(), 500)
return
}
w.WriteHeader(204)
}
开发者ID:dustin,项目名称:sallingshome,代码行数:32,代码来源:admin.go
示例11: view
func view(rw http.ResponseWriter, req *http.Request) {
s := req.FormValue("encoded_key")
c := appengine.NewContext(req)
k, err := datastore.DecodeKey(s)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
posts := []Post{}
q := datastore.NewQuery("post").Ancestor(k).Order("PostDate")
keys, err := q.GetAll(c, &posts)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
threads := []Thread{}
for i, value := range posts {
threads = append(threads, Thread{value, keys[i].Encode()})
}
t := template.Must(template.ParseFiles("assets/post.html"))
t.ExecuteTemplate(rw, "Post", struct {
Parent string
Thread []Thread
}{
s,
threads,
})
}
开发者ID:SiroDiaz,项目名称:csuf,代码行数:32,代码来源:BulletinBoard.go
示例12: GetProfileForUser
func GetProfileForUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
_, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
var userKey *datastore.Key
if userKey, err = datastore.DecodeKey(mux.Vars(r)["key"]); err != nil {
return http.StatusInternalServerError, err
}
var profiles []model.Profile
keys, err := model.NewQueryForProfile().
Ancestor(userKey).
Limit(1).
GetAll(ctx, &profiles)
if err != nil {
return http.StatusInternalServerError, err
}
if len(keys) != 1 {
return http.StatusNotFound, nil
}
json.NewEncoder(w).Encode(profiles[0].Key(keys[0]))
return
}
开发者ID:flowlo,项目名称:coduno-api,代码行数:25,代码来源:profile.go
示例13: editpost
func editpost(rw http.ResponseWriter, req *http.Request) {
c := appengine.NewContext(req)
s := req.FormValue("encoded_key")
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
}
if mypost.Author == user.Current(c).String() {
message := mypost.Message
title := "Edit a Post"
t := template.Must(template.ParseFiles("assets/edit.html"))
t.ExecuteTemplate(rw, "New", struct {
Title string
Message string
ID string
Parent string
}{Title: title, Message: message, ID: s})
} else {
http.Redirect(rw, req, "/", http.StatusOK)
}
}
开发者ID:SiroDiaz,项目名称:csuf,代码行数:28,代码来源:BulletinBoard.go
示例14: GetResult
func GetResult(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, error) {
if !util.CheckMethod(r, "GET") {
return http.StatusMethodNotAllowed, nil
}
resultKey, err := datastore.DecodeKey(mux.Vars(r)["resultKey"])
if err != nil {
return http.StatusBadRequest, err
}
var result model.Result
if err := datastore.Get(ctx, resultKey, &result); err != nil {
return http.StatusInternalServerError, nil
}
p, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
if p.UserKey.Parent() != nil {
json.NewEncoder(w).Encode(result.Key(resultKey))
return http.StatusOK, nil
}
if !util.HasParent(resultKey, p.UserKey) {
return http.StatusUnauthorized, nil
}
return createFinalResult(ctx, w, resultKey, result)
}
开发者ID:tudorgergely,项目名称:api,代码行数:30,代码来源:result.go
示例15: FinalSubmission
// FinalSubmission makes the last submission final.
func FinalSubmission(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
if r.Method != "POST" {
return http.StatusMethodNotAllowed, nil
}
p, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
var resultKey *datastore.Key
if resultKey, err = datastore.DecodeKey(mux.Vars(r)["resultKey"]); err != nil {
return http.StatusInternalServerError, err
}
if !util.HasParent(p.User, resultKey) {
return http.StatusBadRequest, errors.New("cannot submit answer for other users")
}
var index int
if index, err = strconv.Atoi(mux.Vars(r)["index"]); err != nil {
return http.StatusInternalServerError, err
}
if len(r.URL.Query()["submissionKey"]) == 0 {
return http.StatusOK, nil
}
var submissionKey *datastore.Key
if submissionKey, err = datastore.DecodeKey(r.URL.Query()["submissionKey"][0]); err != nil {
return http.StatusInternalServerError, err
}
var result model.Result
if err = datastore.Get(ctx, resultKey, &result); err != nil {
return http.StatusInternalServerError, err
}
result.FinalSubmissions[index] = submissionKey
if _, err = result.Put(ctx, resultKey); err != nil {
return http.StatusInternalServerError, err
}
w.Write([]byte("OK"))
return
}
开发者ID:flowlo,项目名称:coduno-api,代码行数:46,代码来源:submission.go
示例16: UpdateAnyComplaint
func (cdb ComplaintDB) UpdateAnyComplaint(complaint types.Complaint) error {
if k, err := datastore.DecodeKey(complaint.DatastoreKey); err != nil {
return err
} else {
complaint.Version = kComplaintVersion
_, err := datastore.Put(cdb.Ctx(), k, &complaint)
return err
}
}
开发者ID:skypies,项目名称:complaints,代码行数:10,代码来源:update.go
示例17: decodeKey
// decodeKey safely decodes the specified key string, returning
// nil if there is a decoding error.
func decodeKey(k string) *datastore.Key {
if k == "" {
return nil
}
key, err := datastore.DecodeKey(k)
if err != nil {
return nil
}
return key
}
开发者ID:ronoaldo,项目名称:aetools,代码行数:12,代码来源:bundle.go
示例18: makeStatusUpdateFunc
func makeStatusUpdateFunc(c context.Context, ds appwrap.Datastore, pipeline MapReducePipeline, urlStr string, taskKey string) StatusUpdateFunc {
return func(format string, paramList ...interface{}) {
msg := fmt.Sprintf(format, paramList...)
if key, err := datastore.DecodeKey(taskKey); err != nil {
logError(c, "failed to decode task key for status: %s", err)
} else if _, err := updateTask(ds, key, "", 0, msg, nil); err != nil {
logError(c, "failed to update task status: %s", err)
}
}
}
开发者ID:pendo-io,项目名称:mapreduce,代码行数:10,代码来源:mapreduce.go
示例19: DecodeDatastoreKey
func DecodeDatastoreKey(d *Decoder) (*ds.Key, error) {
v, err := d.DecodeString()
if err != nil {
return nil, err
}
if v == "" {
return nil, nil
}
return ds.DecodeKey(v)
}
开发者ID:anmic,项目名称:msgpack,代码行数:10,代码来源:appengine.go
示例20: SaveBoardState
// 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
}
开发者ID:jward6,项目名称:gopandemus,代码行数:56,代码来源:datastore.go
注:本文中的google/golang.org/appengine/datastore.DecodeKey函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论