OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package example |
| 6 |
| 7 import ( |
| 8 "golang.org/x/net/context" |
| 9 "infra/gae/libs/wrapper" |
| 10 "infra/gae/libs/wrapper/gae" |
| 11 |
| 12 "github.com/GoogleCloudPlatform/go-endpoints/endpoints" |
| 13 ) |
| 14 |
| 15 // CASReq is the input for the CAS RPC |
| 16 type CASReq struct { |
| 17 Name string `endpoints:"required"` |
| 18 |
| 19 OldVal int64 `json:",string"` |
| 20 NewVal int64 `json:",string"` |
| 21 } |
| 22 |
| 23 // CAS does an atomic compare-and-swap on a counter. |
| 24 func (Example) CAS(c endpoints.Context, r *CASReq) (err error) { |
| 25 success := false |
| 26 ds := wrapper.GetDS(gae.Use(context.Background(), c)) |
| 27 err = ds.RunInTransaction(func(context.Context) error { |
| 28 ctr := &Counter{ID: r.Name} |
| 29 if err := ds.Get(ctr); err != nil { |
| 30 return err |
| 31 } |
| 32 if ctr.Val == r.OldVal { |
| 33 success = true |
| 34 ctr.Val = r.NewVal |
| 35 _, err := ds.Put(ctr) |
| 36 return err |
| 37 } |
| 38 success = false |
| 39 return nil |
| 40 }, nil) |
| 41 if err == nil && !success { |
| 42 err = endpoints.ConflictError |
| 43 } |
| 44 return |
| 45 } |
| 46 |
| 47 func init() { |
| 48 mi["CAS"] = &endpoints.MethodInfo{ |
| 49 Path: "counter/{Name}/cas", |
| 50 Desc: "Compare and swap a counter value", |
| 51 } |
| 52 } |
OLD | NEW |