-
Notifications
You must be signed in to change notification settings - Fork 17
/
safe.go
84 lines (67 loc) · 1.69 KB
/
safe.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"sync"
"time"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
var globalDB *mgo.Database
var account = "appleboy"
var mu = &sync.Mutex{}
type currency struct {
ID bson.ObjectId `json:"id" bson:"_id,omitempty"`
Amount float64 `bson:"amount"`
Account string `bson:"account"`
Code string `bson:"code"`
}
// Random get random value
func Random(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max-min+1) + min
}
func pay(w http.ResponseWriter, r *http.Request) {
entry := currency{}
//Solution here, Lock other thread access this section of code until it's unlocked
mu.Lock()
defer mu.Unlock()
// step 1: get current amount
err := globalDB.C("bank").Find(bson.M{"account": account}).One(&entry)
if err != nil {
panic(err)
}
wait := Random(1, 100)
time.Sleep(time.Duration(wait) * time.Millisecond)
//step 3: subtract current balance and update back to database
entry.Amount = entry.Amount + 50.000
err = globalDB.C("bank").UpdateId(entry.ID, &entry)
if err != nil {
panic("update error")
}
fmt.Printf("%+v\n", entry)
io.WriteString(w, "ok")
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
session, _ := mgo.Dial("localhost:27017")
globalDB = session.DB("logs")
globalDB.C("bank").DropCollection()
user := currency{Account: account, Amount: 1000.00, Code: "USD"}
err := globalDB.C("bank").Insert(&user)
if err != nil {
panic("insert error")
}
log.Println("Listen server on " + port + " port")
http.HandleFunc("/", pay)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}