iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 22
0
自我挑戰組

Go to 放棄系列 第 22

go note => mongodb part1

  • 分享至 

  • xImage
  •  
package main

import (
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"time"

	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
)

var globalDB *mgo.Database
var account = "golang"

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{}
	// step 1: get current amount
	err := globalDB.C("test").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("test").UpdateId(entry.ID, &entry)

	if err != nil {
		panic("update error")
	}

	fmt.Printf("%+v\n", entry)

	io.WriteString(w, "ok")
}

func main() {
	session, _ := mgo.Dial("172.20.10.10:27017")
	globalDB = session.DB("queue")
	globalDB.C("test").DropCollection()

	user := currency{Account: account, Amount: 1000.00, Code: "USD"}
	err := globalDB.C("test").Insert(&user)

	if err != nil {
		panic("insert error")
	}

	log.Println("Listen server on 3001 port")
	http.HandleFunc("/", pay)
	http.ListenAndServe(":3001", nil)
}

something error...


上一篇
go note => go docker health check
下一篇
just intstalling mongo in pi 3
系列文
Go to 放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言